while loop - Control Menu in Java without case/break -


i'm trying create menu in java without case/breaks , having 2 issues. (1) when run program input should skip .hasnextint() while loop im having re-input user data program end. (2) .hasnextint() while loop not preventing associated error of user inputting wrong type of data. code still crashing string input instead of user being caught in while loop.

public static void menu(library library){      scanner keyboard = new scanner(system.in);     int selection = 999999;      while(selection < 1 || selection > 5){          system.out.println("1. display books");         system.out.println("2. add book");         system.out.println("3. delete book");         system.out.println("4. exit program");          selection = keyboard.nextint();          while(!keyboard.hasnextint()){             system.out.println("re-enter integer value");             selection = keyboard.nextint();         } 

main calls menu.

your current code close, handling non integer inputs incorrectly. consider using following pattern:

while (!keyboard.hasnextint()) {     keyboard.next();     system.out.println("re-enter integer value"); } 

in loop trying consume integer if next token not integer. obviously, doesn't make sense , won't work intended.

the scanner#hasnextint() method block until can determine next token either or not integer. if not integer, above while loop consume next token , repeat. if scanner determines valid integer available, can use value.

while (selection < 1 || selection > 5) {     system.out.println("1. display books");     system.out.println("2. add book");     system.out.println("3. delete book");     system.out.println("4. exit program");      while (!keyboard.hasnextint()) {         keyboard.next();         system.out.println("re-enter integer value");     }     selection = keyboard.nextint(); } 

Comments

Popular posts from this blog

ubuntu - PHP script to find files of certain extensions in a directory, returns populated array when run in browser, but empty array when run from terminal -

php - How can i create a user dashboard -

javascript - How to detect toggling of the fullscreen-toolbar in jQuery Mobile? -