patternjavaMajor
FizzBuzz implementation
Viewed 0 times
implementationfizzbuzzstackoverflow
Problem
The common FizzBuzz implementation I saw is using a check for % 15 for printing "FizzBuzz"
Would you let me know if there is anything wrong / better with this approach?
Would you let me know if there is anything wrong / better with this approach?
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
boolean fizzOrBuzz = false;
if (i % 3 == 0) {
System.out.print("Fizz");
fizzOrBuzz = true;
}
if (i % 5 == 0) {
System.out.print("Buzz");
fizzOrBuzz = true;
}
if (fizzOrBuzz) {
System.out.println();
} else {
System.out.println(String.valueOf(i));
}
}
}
}Solution
Let's compare your version to the
The
% 15 version:public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 15 == 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(String.valueOf(i));
}
}
}
}The
% 15 version is simpler and easier to read. This version neatly delineates the problem into the 4 different cases, and handles each case. In contrast, your version introduces a boolean logic flag (which I consider to be a significant anti-pattern) and a not entirely intuitive dependence on the order of the if statements.Code Snippets
public class FizzBuzz {
public static void main(String[] args) {
for (int i = 1; i <= 100; i++) {
if (i % 15 == 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(String.valueOf(i));
}
}
}
}Context
StackExchange Code Review Q#11489, answer score: 29
Revisions (0)
No revisions yet.