我试图让用户有机会在引入会产生错误但又无法正常工作的东西之后重复输入,因为一旦发现 错误, 就不会再次执行try东西,而是直接进入catch东西,生成一个永恒的东西。柱。这是我的代码:
while (err==1){ err=0; try{ dim = keyboard.nextInt(); } catch(Exception e){ System.out.println("Oops! What you entered is not an integer."); err=1; } }
输入非整数时,对的Scanner调用nextInt()不会消耗非整数。您需要致电keyboard.next()(或keyboard.nextLine())使用它。就像是,
Scanner
nextInt()
keyboard.next()
keyboard.nextLine()
try { dim = keyboard.nextInt(); } catch (Exception e) { System.out.printf("%s is not an integer.%n", keyboard.next()); err = 1; }