I wanted to create a FizzBuzz in Java that is supposed to be open for extension.
So the initial problem is the good old, if divisible by 3 print fizz, if divisible by 5 print buzz, if divisible by both print fizzbuzz, otherwise print the number itself.
But I want to be able to change the numbers that we test against (3 and 5 can become 4 and 6) and the words we print (fizz and buzz may be come foo and bar). And there may be new ones added, such as 7, qux..
Here is what I came up with, any suggestions are welcome:
import java.util.*;
import java.util.function.Function;
import java.util.function.IntPredicate;
class App {
public static void main(String[] args) {
Function<Integer, IntPredicate> divisibilityPredicateBuilder
= isDivisibleBy -> x -> x % isDivisibleBy == 0;
final Map<Integer, String> fizzersBuzzers = new HashMap<>();
fizzersBuzzers.put(3, "fizz");
fizzersBuzzers.put(5, "buzz");
for (int i = 1; i < 101; i++) {
String fizzBuzz = "";
for (Integer fizzerBuzzer : fizzersBuzzers.keySet()) {
if (divisibilityPredicateBuilder.apply(fizzerBuzzer).test(i)) {
fizzBuzz += fizzersBuzzers.get(fizzerBuzzer);
fizzBuzz += " ";
}
}
if (fizzBuzz.isEmpty()) {
fizzBuzz = String.valueOf(i);
}
System.out.println(fizzBuzz.trim());
}
}
}
1 Answer 1
You used a HashMap, where the iteration order is arbitrary. There is no guarantee whether you'll get "fizz buzz" or "buzz fizz"!
-
\$\begingroup\$ yes very good catch Must use sortedmap \$\endgroup\$Koray Tugay– Koray Tugay2018年10月26日 14:00:13 +00:00Commented Oct 26, 2018 at 14:00
Explore related questions
See similar questions with these tags.