我不明白这其中的逻辑。如果我运行此代码并输入一个非整数,例如字母 f,我会陷入输出两个 println 的无限循环,并且我没有机会再次向扫描仪输入整数……它只是不断吐出话到控制台。
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);//<<<<<SCANNER HERE
int opponents = 0;
boolean opponentsCreated = false;
while(opponentsCreated == false)
{
try
{
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
if(tempOpponents > 0)
{
opponents = tempOpponents;
opponentsCreated = true;
}
}
catch(InputMismatchException notAValidInt)
{
System.out.println("Not valid - must be a number greater than 0 ");
}
}
}
但是,如果我只是将 Scanner 更改为在 while 循环中声明,那么程序会突然按预期工作:
public static void main(String[] args) {
int opponents = 0;
boolean opponentsCreated = false;
while(opponentsCreated == false)
{
Scanner scan = new Scanner(System.in);//<<<<<SCANNER HERE
try
{
System.out.print("How many players: ");
int tempOpponents = scan.nextInt();
if(tempOpponents > 0)
{
opponents = tempOpponents;
opponentsCreated = true;
}
}
catch(InputMismatchException notAValidInt)
{
System.out.println("Not valid - must be a number greater than 0 ");
}
}
}
老实说,我只是在这里坐了 2 个小时,试图弄清楚我的程序到底出了什么问题,结果却发现这是我声明我的 Scanner 的问题,即使在两个版本的代码中,Scanner 都没有超出范围。所以现在我真的很好奇为什么它会这样工作