-the above link is the link to the project I am currently having trouble with. I have managed to make it up to part 6, where you are asked to replace each multiple of 3, 5, or 3 and 5 with fizz, buzz, and fizzbuzz respectively. I’ve managed to utilize the modulo method in order to find each element of the list that are multiples of 3 5 or both, but I am confused as to how I can actually REPLACE the number with the word (i.e, replace the number 3 with fizz).
Here is my code so far:
public class FizzBuzz {
public static void main (Stringargs) {
int i;
for (i = 1; i <= 100; i++) {
System.out.println(i);
if (i % 3 == 0) {
System.out.println("Fizz");
}
else if (i % 5 == 0) {
System.out.println("Buzz");
}
else if (i % 3 == 0 && i % 5 == 0){
System.out.println("FizzBuzz");
}
}
The way your code is right now, first you’re printing the number no matter what it is. Then, additionally, if the number is a multiple of 3, 5 or both, it prints the words.
I would wrap this line of code:
System.out.println(i)
inside an else block after all your other conditions. That way, if the number is a multiple of 3, 5 or 3 and 5 it will only print the text. And of the number doesn’t meet any of those conditions, well, it simply prints the number.
Thank you for your timely response, but I don’t think I implemented the System.out.println(i) properly the way you have advised me to. This is what I put, and it still doesn’t work.
public class FizzBuzz {
public static void main (Stringargs) {
int i;
for (i = 1; i <= 100; i++) {
System.out.println(i);
if (i % 3 == 0) {
System.out.println("Fizz");
}
else if (i % 5 == 0) {
System.out.println("Buzz");
}
else if (i % 3 == 0 && i % 5 == 0){
System.out.println("FizzBuzz");
}
else
System.out.println(i);
}
}
}
I’m pretty sure the way I’m wrapping the code in an else block after my conditions is incorrect, please advise if you can, much appreciated!