可能遗漏了一些非常愚蠢的东西,但我的 while 循环不会停止打印错误消息。
有人可以快速浏览一下并为我指明正确的方向吗?
package week5;
import java.util.*;
public class Week5 {
public static void main(String[] args) {
Scanner myKeyboard = new Scanner(System.in);
inputInt();
}
public static int inputInt(){
Scanner myKeyboard = new Scanner(System.in);
System.out.println("Enter number:");
int num;
boolean carryOn = true;
while (carryOn = true) {
{
try {
num = myKeyboard.nextInt();
carryOn = false;
}
catch (Exception e) {
System.out.println ("Integers only");
}
}
}
return 0;
}
最佳答案
这一行就是问题所在
while (carryOn = true) {
您没有使用比较运算符 ==
,而是使用赋值运算符 =
。所以本质上,你在每次迭代中将 carryOn
设置为 true
,然后自动运行循环体,因为条件基本上变成了
while (true) {
只需将该问题行更改为
while (carryOn == true) {
关于java - while 循环不会因异常而停止循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19769380/