exception handling - Why doesn't scanner ask for an other input in a try-catch while loop java -


suppose need keep on asking user till enters double.

what did used while loop , checking if there exception or not.

if there exception, go , ask next input.

double bal = 0; scanner sc = new scanner(system.in); while (true) {     try {         system.out.println("enter balance");         bal = sc.nextdouble();         break;         } catch (exception e) {           system.out.println("that isn't number");     } } system.out.println("bal " + bal); sc.close(); 

but if enter non-double doesn't ask next input, keeps on printing 2 lines ending in infinite loop.

enter balance xyz isn't number enter balance isn't number enter balance isn't number enter balance isn't number .... 

what i'm missing?

you need discard previous input stream calling sc.next() in catch block. sadly, scanner not automatically when input fails.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -