I decided to take on the FizzBuzz challenge with as twist that I would use Java 8 concepts to make it a bit modular, yet still let it be a short, readable and understandable program.
This in contrary to some gem I found on the net: FizzBuzzEnterpriseEdition
The problem description:
Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz"
Here's my code:
public class FizzBuzz {
private static Stream<String> fizzBuzz(final int min, final int max) {
if (min < 0) {
throw new IllegalArgumentException("min is negative: min = " + min);
}
if (min > max) {
throw new IllegalArgumentException("min > max: min = " + min + " / max = " + max);
}
return IntStream.rangeClosed(min, max)
.mapToObj(FizzBuzz::fizzBuzzify);
}
private static String fizzBuzzify(final int value) {
StringBuilder stringBuilder = new StringBuilder();
boolean toDefault = true;
if (value % 3 == 0) {
stringBuilder.append("Fizz");
toDefault = false;
}
if (value % 5 == 0) {
stringBuilder.append("Buzz");
toDefault = false;
}
return (toDefault) ? String.valueOf(value) : stringBuilder.toString();
}
public static void main(String[] args) {
fizzBuzz(1, 100).forEach(System.out::println);
}
}
I'm still looking for a nicer way to write fizzBuzzify
, my intention however is to not hardcode the if (value % 15 == 0)
similarly if (value % 3 == 0 && value % 5 == 0)
, because it creates a sort of illogical operation precedence, being that you absolutely need to write the if (value % 15 == 0)
case up front, followed by the 3-case and the 5-case (or vica versa).