while循环不能使用Try / Catch语句
我试图让用户有机会在介绍产生错误的东西之后重复输入但是有些东西不起作用,因为一旦错误被捕获,尝试的东西不再被执行,而是直接进入捕获的东西产生永恒cicle。 这是我的代码:
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()
)来使用它。 就像是,
try { dim = keyboard.nextInt(); } catch (Exception e) { System.out.printf("%s is not an integer.%n", keyboard.next()); err = 1; }
每次用户输入后,您不会清除/刷新扫描仪缓冲区。
-
在while循环结束之前使用
keyboard.nextLine()
(在catch块之后)要么
-
在while循环中声明scanner对象本身
Scanner keyboard = new Scanner(System.in);
看到这个
干杯!
问题在于input.nextInt()
命令只读取int值。 如果您通过Scanner#nextLine
读取输入并使用Integer#parseInt(String)方法将输入转换为整数,那就更好了。
这对我有用。
public static void main(String[] args) { int err = 1; Scanner keyboard = new Scanner(System.in); while (err == 1) { err = 0; try { int dim = Integer.parseInt(keyboard.nextLine()); System.out.println("done.. exit"); } catch (Exception e) { System.out.println("Ups! What you entered is not an integer."); err = 1; } } }
产量
dd Ups! What you entered is not an integer. 23 done.. exit
next()只能读取输入直到空格。 它无法读取由空格分隔的两个单词。 此外,next()在读取输入后将光标放在同一行。
nextLine()读取包含单词之间空格的输入(即,它读取直到行尾\ n)。 读取输入后,nextLine()将光标定位在下一行。
读取整行,你可以使用nextLine()