7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Javaの小枝] JavaでPPAP

Last updated at Posted at 2016-11-25

参加せざるを得ない

Ppap.java
public class Ppap {

	enum Word {
		pen, pinapple, apple;
		Word talk() {System.out.println("talk : " + this); return this;}
	}
	
	enum PpapState {
		initial {PpapState transition(Word word) {return word == Word.pen      ? p    : initial;}},
		p       {PpapState transition(Word word) {return word == Word.pinapple ? pp   : initial;}},
		pp      {PpapState transition(Word word) {return word == Word.apple    ? ppa  : initial;}},
		ppa     {PpapState transition(Word word) {return word == Word.pen      ? ppap : initial;}},
		ppap;
		PpapState transition(Word next) {throw new InternalError();}
	}
	
	public static void main(String[] args) {
		Random random = new Random();
		
		for (PpapState state = PpapState.initial; state != PpapState.ppap; ) {
			state = state.transition(Word.values()[random.nextInt(3)].talk());
		}
		System.out.println("finish : Pen Pinapple Apple Pen!");
	}

}

心掛けたこと

  • 状態遷移には、いかにも状態遷移を記述しているっぽいコードを使う
  • 話す単語と状態は別の enum で(これはhmhmshさんの前記事のコメントでも指摘されていたけど)
  • 一目でコードの挙動がわかるように書く
7
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?