FizzBuzz Challenge help

I am having some trouble trying to figure out why my code is not printing “Fizzbuzz”. I can get “Fizz” and “Buzz” to print correctly.

Here is my code below. Any help would be appreciated.

public class FizzBuzz{

public static void main (String args){

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 % 15 == 0){

System.out.println(“FizzBuzz”);

}

System.out.println(i);

}

}

}

Welcome to the forums :slight_smile:

What happens if you take out the else (keep the if's)?

In the future, remember to format your code with the </> button :slight_smile: It’ll make it easier for people to help…

2 Likes

You got to make the statement check if i is divisible by both 3 and 5 first before doing each individually. So here is my code.

public class FizzBuzz {

public static void main(String args) {

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

  if (i % 5 == 0 && i % 3 == 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 hope this helped you understand!

1 Like

The concept is that for every one if() there must be one else() to match it. In between these two, there can be as many else if() as you want. Also the else() and else if() must be placed after the return bracket } on the same line

Example code:

if(){

}else if(){

}else{

}

Must there?

1 Like