Saturday 15 May 2010

if statement - Java, BufferedReader, restrict user input, y/n -



if statement - Java, BufferedReader, restrict user input, y/n -

my question how restrict user input y/n or y/n(in java). i'm using equals() , plan alter them equalsignorecase(), should take care of case part. however, doesn't stop user entering other characters(ex: h or h). when character besides y or n entered programme proceeds straight "thanks playing message" , end of game.

i relatively new programming, please provide examples suggestion, preferably finish example. goes long way me. additional, if sense section of code written in improve way, open rewrites, 1 time 1 time again please provide total example.

i realize question little broad stackoverflow utilize insight of more experienced programs. give thanks time.

// creates instance of bufferedreader // prompts user play game 1 time again // places user input in seek // if user wants play again, phone call startgame() // if user dosen't want play again, maintain asking anyways private void showplayagainmessage() { bufferedreader br = new bufferedreader(new inputstreamreader(system.in)); system.out.println(); system.out.println("do want play again? (y/n)"); seek { string playagain = br.readline(); // want play again? y. if(playagain.equals("y")) { startgame();//else prompt question if else } // want play again? n. else if(playagain.equals("n")) { system.out.println(); system.out.println("last chance. play again? (y/n)"); playagain = br.readline(); // lastly chance. play again? y. if(playagain.equals("y")) { startgame(); } // lastly chance. play again? n. else if(playagain.equals("n")) { system.out.println(); system.out.println("how minesweeper? (y/n)"); playagain = br.readline(); // how minesweeper? y. if(playagain.equals("y")) { system.out.println(); system.out.println("i wish had minesweeper..."); system.out.println("lots of hangman though...hangman? (y/n)"); playagain = br.readline(); // lots of hangman though...hangman? y. if(playagain.equals("y")) { startgame(); } // lots of hangman though...hangman? n. else if (playagain.equals("n")) { system.out.println(); system.out.println("ok..."); } } } } }

this string of question looks annoying, if must, can utilize while loop switch statement implements state machine.

int state = 0; while (state < 4) { switch (state) { case 0: system.out.println("do want play again? (y/n)"); break; case 1: system.out.println("last chance. play again? (y/n)"); break; case 2: system.out.println("how minesweeper? (y/n)"); break; case 3: system.out.println("i wish had minesweeper..."); system.out.println("lots of hangman though...hangman? (y/n)");break; } string playagain = br.readline(); if(playagain.equals("y")) { startgame(); state = 0; } else if(playagain.equals("n")) { state++; } } system.out.println("ok...");

each "n" reply advance next question. illegal input show current question again.

java if-statement bufferedreader nested-if

No comments:

Post a Comment