java - Code not exiting while loop (trying to catch exceptions) -
this question has answer here:
- java scanner exception handling 4 answers
i have written simple code (n1 / n2 = sum) whilst trying learn try / catch exception handling.
i have / while loop supposed make x = 2 when run successfully. if not, x = 1, user input can entered again.
the code compiles , runs if try, example n1 = 10, n2 = stackoverflow, prinln caught exception runs forever!
why loop stuck?
thanks in advance
import java.util.*; public class exceptionhandlingmain { public static void main(string[] args) { scanner input = new scanner(system.in); int x = 1; // x set 1 { // start of loop try { system.out.println("enter numerator: "); int n1 = input.nextint(); system.out.println("enter divisor"); int n2 = input.nextint(); int sum = n1 / n2; system.out.println(n1 + " divided " + n2 + " = " + sum); x = 2; // when code completed successfully, x = 2 , / while loop exits } catch (exception e) { system.out.println("you made mistake, moron!"); } } while (x == 1); } }
add input.nextline()
in catch
block clear line read.