Java Arena
Step 5 of 6

Most specific condition first

When conditions overlap, the order of an else if chain decides the answer, and the most specific case has to come first. The classic example is FizzBuzz: print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number itself otherwise.

int number = 15;
if (number % 3 == 0 && number % 5 == 0) {
    System.out.println("FizzBuzz");
} else if (number % 3 == 0) {
    System.out.println("Fizz");
} else if (number % 5 == 0) {
    System.out.println("Buzz");
} else {
    System.out.println(number);
}
Output
FizzBuzz

15 is a multiple of 3, so if the number % 3 == 0 check came first, it would print Fizz and never reach the combined case. Checking "both" first works, because every later branch can then assume that "both" was false.

Your task

Challenge 1 of 3

Read a number and print FizzBuzz, Fizz, Buzz or the number itself, by the rules above. For the input 9 the program prints:

Fizz

Challenge 2

Read a year and print Leap year or Not a leap year. The rules of the calendar we use:

  • a year divisible by 4 is a leap year,
  • except a year divisible by 100, which is not,
  • except a year divisible by 400, which is.

For the input 2024 the program prints Leap year.

Challenge 3

Read a whole number and classify it:

  • divisible by both 2 and 3: Divisible by 6
  • divisible by 2 only: Even
  • divisible by 3 only: Multiple of three
  • anything else: Other

For the input 12 the program prints Divisible by 6.