我正在使用 try-catch 异常处理编写此程序:
Scanner keyboard = new Scanner(System.in);
String[] employees = new String[5];
boolean done1 = false;
//input and error exception for entering employee names into an array
for (int i = 0; i < 5; i++)
{//begin for
while (!done1)
{//begin while
System.out.println("Please enter employee's name: ");
try
{//begin try
employees[i] = keyboard.nextLine();
if (employees[i].length() == 0)
throw new Exception("No name was entered.");
if (employees[i].length() >= 31)
throw new Exception("Name entered contains too many "
+ "characters");
for (int check = 0; check < employees[i].length(); check++)
{//begin for
if(Character.isDigit(employees[i].charAt(check)))
throw new Exception("Input contains invalid "
+ "charaters.");
}//end for
done1 = true;
}//end try
catch (Exception a)
{//begin catch
System.out.println("Error: " + a.getMessage());
}//end catch
}//end while
}//end for
当我运行该程序时,它会退出 for 循环,并且只输入 i 的第一个实例,其余的都为空。我怎样才能让程序停留在这个循环中并让它保持错误检查?
最佳答案
您的 done1
变量在第一个循环后保持 true
,导致后续 while
语句不进入循环体。
最好完全消除 done1
变量,并使用如下结构:
for (...) {
while (true) {
try {
// get user input
break;
} catch (Exception e) {
// ..
}
}
}
关于java - 嵌套循环在 Java 程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5358543/