[英]Looping try-catch isn't working
How would I properly loop this try catch statement? 我将如何正确循环此try catch语句? From what I'm aware, the playerIntInput = reader.nextInt();
据我所知, playerIntInput = reader.nextInt();
within the try block is executed and it catches the exception if one exists, this should cause the loop = false
to never be reached. try块中的代码将被执行,如果存在则捕获异常,这将导致loop = false
永远不会到达。 Then it output the message in the catch block and it should loop back to the try and ask for input again. 然后,它在catch块中输出消息,并且应该循环回到try并再次请求输入。 Instead I just get an infinitely looped output from the catch block. 相反,我只是从catch块获得了无限循环的输出。
void CheckInput(int playerIntInput) {
boolean loop = true;
while(loop=true) {
try {
playerIntInput = reader.nextInt();
loop = false;
}
catch(InputMismatchException e) {
System.out.println("Invalid character was used, try again.");
}
}
}
You used the assignment operator =
, so loop
is always true
when checked, instead of the ==
operator. 您使用了赋值运算符=
,因此选中时loop
始终为true
,而不是==
运算符。 You could use while(loop == true)
, but loop
is already a boolean
. 您可以使用while(loop == true)
,但是loop
已经是一个boolean
。 The simplest solution is while(loop)
. 最简单的解决方案是while(loop)
。
Also, if there's an error in nextInt
, it won't consume the input. 另外,如果nextInt
存在错误,则不会消耗输入。 Call next()
in the catch
block to consume the non-numeric input and advance past it. 在catch
块中调用next()
以使用非数字输入并前进通过它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.