Skip to content

Project: FizzBuzz

Write a program that behaves as such:

  1. Enter a number
  2. If the number is divisible by 5 print “Fizz”
  3. If the number is divisible by 3 print “Buzz”
  4. If the number is divisible by both 3 and 5 print “FizzBuzz”
  5. If the number is not divisible by either return the entered number.
import java.util.Scanner;
public class FizzBuzz {
    public static void main(String[] args) {
        final int FIVE = 5;
        final int THREE = 3;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Number: ");
        int inputNumber = scanner.nextInt();
        Boolean divisibleByFive = (inputNumber / FIVE ) * FIVE == inputNumber;
        Boolean divisibleByThree = (inputNumber / THREE ) * THREE == inputNumber;
        if (divisibleByFive && divisibleByThree){
            System.out.println("FizzBuzz");
        }
        else if (divisibleByThree){
            System.out.println("Buzz");
        }
        else if (divisibleByFive){
            System.out.println("Fizz");
        } else {
            System.out.println(inputNumber);
        }
    }
}

After reviewing the code whilst the way we wrote our code was mostly we could make a significant change to our divisible Boolean to clean it up further. Here were the take aways.

  • Use the modulus operator instead of our division multiplication method.

Whilst there was no discussion about setting our five and three to a final variable I have chosen to do this as the program is very specific on those outputs. I wanted to ensure there was no room for error in future updates to the program. Below is my updated coded.

    public static void main(String[] args) {
        final int FIVE = 5;
        final int THREE = 3;
        Scanner scanner = new Scanner(System.in);
        System.out.print("Number: ");
        int inputNumber = scanner.nextInt();
        Boolean divisibleByFive = inputNumber % FIVE == 0;
        Boolean divisibleByThree = inputNumber % THREE == 0;
        if (divisibleByFive && divisibleByThree){
            System.out.println("FizzBuzz");
        }
        else if (divisibleByThree){
            System.out.println("Buzz");
        }
        else if (divisibleByFive){
            System.out.println("Fizz");
        }
        else {
            System.out.println(inputNumber);
        }
    }