Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
FizzBuzz Java (using CharSequence)
public class Main {
public static void main(String[] args) throws Exception {
System.out.println(new StringBuilderFizzBuzz(100).get());
System.out.println(new StringFizzBuzz(100).get());
}
private static abstract class FizzBuzz<C extends CharSequence> {
private final int limit;
private final C appendable;
FizzBuzz(int limit, C appendable) {
this.limit = limit;
this.appendable = build(appendable, 1);
}
private C build(C appendable, int i) {
if(i%3 == 0) {
appendable = append(appendable, "Fizz");
}
if(i%5 == 0) {
appendable = append(appendable, "Buzz");
} else if(i%3 != 0) {
appendable = append(appendable, Integer.toString(i,10));
}
return (i < this.limit) ? build(append(appendable, ","), ++i) : appendable;
}
abstract C append(C appendable, String value);
C get() {
return this.appendable;
}
}
private static class StringBuilderFizzBuzz extends FizzBuzz<StringBuilder> {
StringBuilderFizzBuzz(int i) {
super(i, new StringBuilder());
}
@Override
StringBuilder append(StringBuilder appendable, String value) {
return appendable.append(value);
}
}
private static class StringFizzBuzz extends FizzBuzz<String> {
StringFizzBuzz(int i) {
super(i, "");
}
@Override
String append(String appendable, String value) {
appendable = appendable + value;
return appendable;
}
}
}
Owner

VallaDanger commented Apr 22, 2016

absolutely unnecessary way to solve the FizzBuzz problem, but yet another way to solve it...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment