java - How to add check for string in do while -
scanner in = new scanner(system.in); int menuitem; do{ system.out.println("choose menu item 1,2,3,4,5: "); menuitem = in.nextint(); }while(menuitem >5); //i tried use //while(menuitem >5 || !in.hasnextint());---> doesnt work
it shows
exception in thread "main" java.util.inputmismatchexception
in code want validate menu item not string type
, not more 5
, repeat choose item menu if input not string type , not more 5
but don't know how validate input if string.
as answer given Φxoce 웃 Пepeúpa, outer while loop run infinitely if user enters no greater 5.
please try this:
1. validate number if string , asked user enter valid number
2.and repeat chhose menu item if correct.
package sample; import java.util.arraylist; import java.util.scanner; public class tets { public static void main(string[] args) { scanner in = new scanner(system.in); int menuitem = 0; { system.out.println("choose menu item 1,2,3,4,5: "); try { menuitem = integer.parseint(in.nextline()); } catch (numberformatexception e) { system.out.println("wrong input, please enter again"); menuitem=0; } } while (menuitem <= 5 && menuitem >=0); system.out.println("you have entered no > 5 or no < 0"); system.out.println("exit"); } } output: choose menu item 1,2,3,4,5: 2 choose menu item 1,2,3,4,5: 4 choose menu item 1,2,3,4,5: wrong input, please enter again choose menu item 1,2,3,4,5: -1 choose menu item 1,2,3,4,5: 6 have entered no > 5 or no < 0 exit
Comments
Post a Comment