我正在使用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的第一个实例,其余的则保持为null。如何让程序保持在这个循环中并让它保持错误检查?
答案 0 :(得分:2)
第一次循环后,done1
变量仍为true
,导致后续的while
语句无法进入循环体。
最好完全消除done1
变量,并使用这样的结构:
for (...) {
while (true) {
try {
// get user input
break;
} catch (Exception e) {
// ..
}
}
}
答案 1 :(得分:1)
将done1
设置回false
。或者插入done1 = false
作为主for
周期中的第一行。
答案 2 :(得分:0)
在try catch
循环中简单地放置另一个for
块可能最简单。抛出异常时,它将使用for
循环的catch
并继续迭代。
这样的事情:
for (int check = 0; check < employees[i].length(); check++)
{//begin for
try {
if(Character.isDigit(employees[i].charAt(check)))
throw new Exception("Input contains invalid "
+ "charaters.");
}
catch(Exception e)
{ //Handle Error
}
}//end for
答案 3 :(得分:0)
您没有正确使用例外...
异常是处理这种逻辑的一种非常昂贵的方式,而你只是创建一个非特定异常并使用它的方法是错误的。例外是为处理程序中可能发生的异常事件而设计的 - 资源不可用性,连接超时等等。
您所看到的问题应该仅通过流量控制来解决。
希望这会有所帮助......
马丁。
聚苯乙烯。你的代码,异常被一些更合理的东西取代,可能看起来像这样:
import java.util.Scanner;
public class SOExample {
/**
* @param args
*/
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
String[] employees = new String[5];
boolean done1 = false;
String strMessage = "";
//input and error exception for entering employee names into an array
for (int i = 0; i < 5; i++)
{//begin for
done1 = false;
while (!done1)
{//begin while
strMessage="";
System.out.println("Please enter employee's name: ");
employees[i] = keyboard.nextLine();
if (employees[i].length() == 0)
strMessage = "No name was entered.";
if (employees[i].length() >= 31)
strMessage = "Name entered contains too many "
+ "characters";
if (strMessage == ""){
for (int check = 0; check < employees[i].length(); check++)
{//begin for
if(Character.isDigit(employees[i].charAt(check))){
strMessage = "Input contains invalid "
+ "charaters.";
break;
}
}//end for
}
done1 = (strMessage == "");
if (!done1){
System.out.println("Error: " + strMessage);
}
}//end while
}//end for
}
}
答案 4 :(得分:0)
第一次进入while循环时,!done1表达式的计算结果为true,因为done1为false。最后你将done1设置为true。当你评估!done1以便再次执行循环时,表达式现在为假,因为你在第一遍中将done1设置为true。