Last active
September 27, 2015 10:58
-
-
Save stuhacking/1259421 to your computer and use it in GitHub Desktop.
Fizz Buzz in Java without using an else clause. (Try not to take it seriously.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
abstract class FizzBuzzState | |
{ | |
protected FizzBuzz fizzbuzz; | |
protected int number; | |
public FizzBuzzState (int num, FizzBuzz f) | |
{ | |
number = num; | |
fizzbuzz = f; | |
} | |
public int getNumber () | |
{ | |
return number; | |
} | |
public FizzBuzzState next () | |
{ | |
int next = number + 1; | |
if (next % 15 == 0) | |
{ | |
return new FizzBuzzFizzBuzzState(next, fizzbuzz); | |
} | |
if (next % 5 == 0) | |
{ | |
return new FizzBuzzBuzzState(next, fizzbuzz); | |
} | |
if (next % 3 == 0) | |
{ | |
return new FizzBuzzFizzState(next, fizzbuzz); | |
} | |
return new FizzBuzzNumState(next, fizzbuzz); | |
} | |
public abstract void doPrint(); | |
} | |
class FizzBuzzFizzState extends FizzBuzzState | |
{ | |
public FizzBuzzFizzState (int n, FizzBuzz f) | |
{ | |
super(n, f); | |
} | |
@Override | |
public void doPrint() | |
{ | |
fizzbuzz.doPrint("Fizz"); | |
} | |
} | |
class FizzBuzzBuzzState extends FizzBuzzState | |
{ | |
public FizzBuzzBuzzState (int n, FizzBuzz f) | |
{ | |
super(n, f); | |
} | |
@Override | |
public void doPrint() | |
{ | |
fizzbuzz.doPrint("Buzz"); | |
} | |
} | |
class FizzBuzzFizzBuzzState extends FizzBuzzState | |
{ | |
public FizzBuzzFizzBuzzState (int n, FizzBuzz f) | |
{ | |
super(n, f); | |
} | |
@Override | |
public void doPrint() | |
{ | |
fizzbuzz.doPrint("FizzBuzz"); | |
} | |
} | |
class FizzBuzzNumState extends FizzBuzzState | |
{ | |
public FizzBuzzNumState (int n, FizzBuzz f) | |
{ | |
super(n, f); | |
} | |
@Override | |
public void doPrint() | |
{ | |
fizzbuzz.doPrint(String.valueOf(number)); | |
} | |
} | |
public class FizzBuzz | |
{ | |
public FizzBuzz (int limit) | |
{ | |
for (FizzBuzzState state = new FizzBuzzNumState(1, this); state.getNumber() <= limit; state = state.next()) | |
{ | |
state.doPrint(); | |
} | |
} | |
public void doPrint(String string) | |
{ | |
System.out.println(string); | |
} | |
public static void main(String[] args) { | |
new FizzBuzz(100); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment