2
\$\begingroup\$

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());
 }
 }
}
asked Oct 26, 2018 at 12:50
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

You used a HashMap, where the iteration order is arbitrary. There is no guarantee whether you'll get "fizz buzz" or "buzz fizz"!

answered Oct 26, 2018 at 13:50
\$\endgroup\$
1
  • \$\begingroup\$ yes very good catch Must use sortedmap \$\endgroup\$ Commented Oct 26, 2018 at 14:00

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.