Since I have completely lost the opportunity to touch Java at work, I thought about how to solve the "Fizz Buzz problem" in various ways using Java.
FizzBuzz.java
/**
*A common method using a for statement.
* @param end The number to end FizzBuzz.
*/
public static void useForLoop(int end) {
for (int i=1; i<=end; i++) {
if (i%3==0 && i%5==0) {
System.out.println("Fizz Buzz");
} else if (i%3==0) {
System.out.println("Fizz");
} else if (i%5==0) {
System.out.println("Buzz");
} else {
System.out.println(i);
}
}
}
FizzBuzz.java
/**
*A method that utilizes the ternary operator.
* @param end The number to end FizzBuzz.
*/
public static void useForLoopWithTertiaryOperator(int end) {
for (int i=1; i<=end; i++) {
System.out.println(
(i%3==0 && i%5==0) ? "Fizz Buzz" : (i%3==0) ? "Fizz" : (i%5==0) ? "Buzz" : i
);
}
}
FizzBuzz.java
import java.util.stream.IntStream;
...
/**
*A method that utilizes the Stream API.
* @param end The number to end FizzBuzz.
*/
public static void useStreamAPI(int end) {
IntStream.rangeClosed(1, end)
.mapToObj(i -> (i%3==0 && i%5==0) ? "Fizz Buzz" : (i%3==0) ? "Fizz" : (i%5==0) ? "Buzz" : i)
.forEach(msg -> System.out.println(msg));
}
Recommended Posts