Anonymous user
FizzBuzz/Java: Difference between revisions
→Recursive: newline for readable output
imported>Er2 (formatting) |
imported>Er2 (→Recursive: newline for readable output) |
||
(4 intermediate revisions by the same user not shown) | |||
Line 59:
if (s.equals(""))
s = n + "";
return fizzBuzz(n-1) + "\n" + s;
}
</syntaxhighlight>
Line 92:
public static void main( String [] args ) {
int [] x = new int [100];
Arrays.setAll(x, j -> j
Arrays.stream(x).forEach(i -> {
if(i == 0) return;
Line 179:
=== Enum-based Declarative ===
With Functional and OO elements
A new rule can be added by adding a single line.
<syntaxhighlight lang="java">
import java.util.Arrays;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public enum FizzBuzz {
Fizz(divisibleBy(3)),
Buzz(divisibleBy(5));
private final IntPredicate test;
FizzBuzz(IntPredicate test) {
this.test = test;
}
static IntPredicate divisibleBy(int i) {
return n -> n % i == 0;
}
String applyRule(int n) {
if (test.test(n))
return name();
return "";
}
static String print(int i) {
String byRules = Arrays.stream(values())
.map(rule -> rule.applyRule(i))
.collect(Collectors.joining());
if (byRules.isEmpty())
return i + "";
return byRules;
}
public static void main(String[] args) {
IntStream.rangeClosed(1, 100)
.mapToObj(FizzBuzz::print)
.forEach(System.out::println);
}
}
</syntaxhighlight>
|