gpt4 book ai didi

java - JAVA中try-catch的死循环

转载 作者:行者123 更新时间:2023-12-02 05:30:24 25 4
gpt4 key购买 nike

所以我想做的是让用户在矩阵中输入一个有效的坐标,即大于-1的INT,

Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>R)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}
while (((coordinates[1]<0)||(coordinates[1]>C)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
break;
}
catch (InputMismatchException e) {
}
}

问题是输入无效输入后会无限循环int R 是行的大小int C 是列的大小

最佳答案

您的问题是您没有处理您捕获的错误。如果您为 nextInt() 方法提供了错误的数字格式,则将抛出 InputMismatchException。然后,因为 catch 不执行任何操作,循环将继续(从头开始),并且扫描器将读取相同的错误值,依此类推...

所以代替这个:

catch (InputMismatchException e) {
}

试试这个:

catch (InputMismatchException e) {
System.out.println("Wrong number entered.");
scanner.nextLine();
}

这样,您将强制扫描仪移过最后一个不正确的输入。

编辑:

你的循环也被破坏了,因为你在读取输入后break。在这种情况下,如果您输入负数,您也会中断并且不会检查循环条件。删除 break 语句,它将按预期工作:

while (((coordinates[0]<0)||(coordinates[0]>R))  && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}

编辑2:

public static void main(final String args[])
{
int maxRowsNumber = 10;
int maxColsNumber = 10;
Scanner scanner = new Scanner (System.in);
int coordinates[] = new int[2];
coordinates[0]=-1;
coordinates[1]=-1;
boolean check = true;
while (((coordinates[0]<0)||(coordinates[0]>maxRowsNumber)) && check) {
System.out.print("Please enter a valid row number:\t");
try {
coordinates[0]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
while (((coordinates[1]<0)||(coordinates[1]>maxColsNumber)) && check) {
System.out.print("Please enter a valid col number:\t");
try {
coordinates[1]=scanner.nextInt();
}
catch (InputMismatchException e) {
System.out.println("That's not a valid number.");
scanner.nextLine();
}
}
System.out.println("Inserted RowsNumber: " + coordinates[0]);
System.out.println("Inserted RowsNumber: " + coordinates[1]);
}

输出:

Please enter a valid row number:    11
Please enter a valid row number: 22
Please enter a valid row number: 10
Please enter a valid col number: 11
Please enter a valid col number: 2
Inserted RowsNumber: 10
Inserted RowsNumber: 2

关于java - JAVA中try-catch的死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25602634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com