java - Why does Scanner#nextInt inside for loop keep throwing an exception? -
java - Why does Scanner#nextInt inside for loop keep throwing an exception? -
i have been learning java , have little uncertainty code :
class apple { public static void main(string[] args) { int[] num = new int[3]; scanner input = new scanner(system.in); (int = 0; < num.length; i++) { seek { num[i] = input.nextint(); } grab (exception e) { system.out .println("invalid number..assigning default value 20"); num[i] = 20; } } (int = 0; < num.length; i++) { system.out.println(num[i]); } } }
i have written little programme handle exception, if user input not int throw exception , assign default value. if set scanner statement within loop, works fine, if take outside assign same value @ exception thrown i.e entering char rather int. if come in integers assign right values in array.
scanner input = new scanner(system.in);
i hope u guys have understood question.
scanner#nextint
doesn't advance past input if fails parse integer, if maintain calling after failure, maintain trying parse same input again, throwing inputmismatchexception
.
you can phone call scanner#next
, ignoring string returns, in catch
block skip invalid input:
try { num[i] = input.nextint(); } grab (exception e) { system.out .println("invalid number..assigning default value 20"); num[i] = 20; input.next(); }
java java.util.scanner
Comments
Post a Comment