Project: FizzBuzz
Write a program that behaves as such:
- Enter a number
- If the number is divisible by 5 print “Fizz”
- If the number is divisible by 3 print “Buzz”
- If the number is divisible by both 3 and 5 print “FizzBuzz”
- If the number is not divisible by either return the entered number.
My Code
Section titled “My Code”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); } }}
Code Review
Section titled “Code Review”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); } }