java - Cannot Figure out how to catch InputMismatchException -
so here current code catching inputmismatchexception error
int weapon = 0 boolean selection = true; while(selection) { try { system.out.println("pick number 1, 2, or 3."); weapon = scan.nextint(); selection = false; } catch(inputmismatchexception e) { system.out.println("choose 1,2,3"); weapon = scan.nextint(); } }
i'm trying make sure int entered , not else. scanner class been implemented , 'scan' act me.
thanks efforts help!
try this:
int weapon = 0; do{ system.out.println("pick number 1, 2, or 3."); if(scan.hasnextint()){ weapon = scan.nextint(); break; }else{ system.out.println("enter integer only"); scan.nextline(); } }while(true);
this make sure integer , keep asking until gets it.