exception - Java: try/catch with InputMismatchException creates infinite loop -
so i'm building program takes ints user input. have seems straightforward try/catch block which, if user doesn't enter int, should repeat block until do. here's relevant part of code:
import java.util.inputmismatchexception; import java.util.scanner; public class except { public static void main(string[] args) { scanner input = new scanner(system.in); boolean berror = true; int n1 = 0, n2 = 0, nquotient = 0; { try { system.out.println("enter first num: "); n1 = input.nextint(); system.out.println("enter second num: "); n2 = input.nextint(); nquotient = n1/n2; berror = false; } catch (exception e) { system.out.println("error!"); } } while (berror); system.out.printf("%d/%d = %d",n1,n2, nquotient); } }
if enter 0 second integer, try/catch it's supposed , makes me put in again. but, if have inputmismatchexception entering 5.5 1 of numbers, shows error message in infinite loop. why happening, , can it? (by way, have tried explicitly typing inputmismatchexception argument catch, didn't fix problem.
you need call next();
when error. advisable use hasnextint()
catch (exception e) { system.out.println("error!"); input.next();// move next other wise exception }
before reading integer value need make sure scanner has one. , not need exception handling that.
scanner scanner = new scanner(system.in); int n1 = 0, n2 = 0; boolean berror = true; while (berror) { if (scanner.hasnextint()) n1 = scanner.nextint(); else { scanner.next(); continue; } if (scanner.hasnextint()) n2 = scanner.nextint(); else { scanner.next(); continue; } berror = false; } system.out.println(n1); system.out.println(n2);
javadoc of scanner
when scanner throws inputmismatchexception, scanner not pass token caused exception, may retrieved or skipped via other method.
Comments
Post a Comment