I'm trying a basic challenge that involves a program counting to 100, and displaying that output while it counts up.

For every multiple of 3; it must print Fizz

For every multiple of 5, it must print Buzz

For every multiple of 3 & 5 it must print FizzBuzz

The code I've written handles System.out on the non-multiple numbers, and the FizzBuzz multiples without issue. However, for the multiples of just 3 and 5 it acts as if I didn't write any "else if" condition. I have been unable to figure out what might be causing this! Here is the code.

Your issue is your first statement. Check your logic:
1. if num is not a multiple of 3 OR if num is not a multiple of 5
2. if num is a multiple of 3 AND if num is not a multiple of 5

Right there is the start of your problem. Your second condition requires num to NOT be a multiple of 5. However, if num is not a multiple of 5, the first if statement's condition is met, so the else statements are never even checked.
This same logistical problem is in your other conditions.

March 7th, 2013, 03:21 PM

angstrem

Re: Conditional Statement Issue *Newbie Help*

Here's the error:

Code :

if (num % 3 != 0 || num % 5 != 0) {
System.out.println(num);
}

It must be

Code :

if (num % 3 != 0 && num % 5 != 0) {
System.out.println(num);
}

You see, this condition goes before your "Fizz" and "Buzz" conditions. But "Fizz" is executed only if num % 5 != 0. And if this condition is true, than the erroneous block's condition holds (that is, num % 3 != 0 || num % 5 != 0). The same thing is for the "Buzz" block.

March 7th, 2013, 03:21 PM

Norm

Re: Conditional Statement Issue *Newbie Help*

With chains of if/else if statements, the first one that is true will be executed. NONE of the others will be tested.
If the first if statement is true none of the other if statements will be tested.

Does this post mean that the first if is true for numbers 1 to 14:

Quote:

1,2,3,4,5 .... 13,14,FizzBuzz

Look at the conditions in the first if and see when it will be false. Right now it is true for numbers 1 thru 14

March 7th, 2013, 03:25 PM

dotChristo

Re: Conditional Statement Issue *Newbie Help*

That makes perfect sense. I can't believe I didn't pick up on that at all. Thanks!