Fizz Buzz。クラスライブラリ


Fizz-Buzz問題をクラスライブラリとして作ってみました。
まー役に立つことはないでしょう(笑)。


FizzBuzzTest.jar


./FizzBuzzTest.java

/**
* 
* FizzBuzzTest
* 
* @author DumBo
* @version 0.01 (Jun 17, 2012)
* 
*/

import jp.regekatsu.game.FizzBuzz;

class FizzBuzzTest {
	
	public static void main(String[] args) {
		
		FizzBuzz fizzBuzz = new FizzBuzz(1, 100);
		
		while(true){
			try {
				Thread.sleep(250);
			} catch(InterruptedException e) {
			}
			
			System.out.print(fizzBuzz.getCount() + "=" 
				+ fizzBuzz.getText() + ", ");
			fizzBuzz.update();
		}
	}
}


./jp/regekatsu/game/FizzBuzz.java

/**
* 
* FizzBuzz
* 
* @author DumBo
* @version 0.01 (Jun 17, 2012)
* 
*/

package jp.regekatsu.game;

public class FizzBuzz {
	
	private int count;
	private int max;
	private String text;
	
	public FizzBuzz() {
		initialize(1, Integer.MAX_VALUE);
		updateText();
	}
	
	public FizzBuzz(int count) {
		initialize(count, Integer.MAX_VALUE);
		updateText();
	}
	
	public FizzBuzz(int count, int max) {
		initialize(count, max);
		updateText();
	}
	
	public void update() {
		updateCount();
		updateText();
	}
	
	public int getCount() {
		return count;
	}
	
	public String getText() {
		return text;
	}
	
	private void initialize(int count, int max) {
		
		if(count <= 0) {
			throw new IllegalArgumentException("初期値は正数を指定してください。");
		}
		if(max < count || max > Integer.MAX_VALUE) {
			throw new IllegalArgumentException("最大値は初期値以上の正数を指定してください。");
		}
		
		this.count = count;
		this.max = max;
		
	}
	
	private void updateCount() {
		if(count < max) {
			count++;
		}
	}
	
	private void updateText() {
		if(count % 3 == 0 && count % 5 == 0) {
			text = "FizzBuzz";
		} else if(count % 3 == 0) {
			text = "Fizz";
		} else if(count % 5 == 0) {
			text = "Buzz";
		} else {
			text = String.valueOf(count);
		}
	}
	
}