javaif-statementfizzbuzz

# Why isn't my FizzBuzz code processing both if statements when they both match?

For those who don't know, FizzBuzz is the following problem:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Every FizzBuzz solution I find is either some crazy esoteric solution made for the sake of being original, or your basic if-else chain:

``````for(int i = 1; i <= 100; i++) {

if(i % 3 == 0 && i % 5 == 0) {
System.out.println("FizzBuzz");
} else if (i % 3 == 0) {
System.out.println("Fizz");
} else if (i % 5 == 0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
``````

I am looking for a simple solution that aims to take out the "FizzBuzz" if statement. I have this in mind:

``````for(int i = 1; i <= 100; i++) {

if (i % 3 == 0)
System.out.print("Fizz");
if (i % 5 == 0)
System.out.println("Buzz")
else
System.out.println(i);
}
``````

But this doesn't work. I assume it would be able to print FizzBuzz by entering both ifs, for Fizz and for Buzz, but if the number is, for example, 3, it would print Fizz3. How do I avoid this?

Solution

• What you're trying to do is

``````if (a)
...
if (b)
...
else // if neigther a nor b
...
``````

This is simply not possible. An `else` can only belong to a single `if`. You have to go with the slightly longer variant.

To avoid doing redundant evaluations of the modulo operator, you could formulate the loop body as

``````boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;

if (fizz)
System.out.print("Fizz");
if (buzz)
System.out.print("Buzz");
if (!(fizz || buzz))
System.out.print(i);

System.out.println();
``````

Another one would be

``````String result = "";

if (i % 3 == 0)   result = "Fizz";
if (i % 5 == 0)   result += "Buzz";
if (result == "") result += i;

System.out.println(result);
``````