很抱歉,如果我的问题看起来有点模糊。
基本上我要做的是使用构造函数对象上的字符串比较进行错误检查,该对象存储在数组中。我认为我有正确的想法:( Count是一个静态int,无论何时在另一个方法中添加员工时都会迭代)
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
for (int i = 0; i < count; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID) == true) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID
+ "'s current title is: "
+ searchArray[i].getEmployeeTitle());
System.out.println(" ");
System.out
.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine().toUpperCase();
if (answer.equals("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
searchArray[i].setEmployeeTitle(newTitle);
searchArray[i].updateTitle(newTitle);
}
if (answer.equals("N")) {
break;
}
} else if (searchID.equals(arrayID) == false) {
System.out.println("Please enter a valid ID!");
}
}
}
这个成功的错误检查,但是因为它正在遍历数组,如果数组元素是&gt;它将在验证消息之前显示错误消息。 0并且在数组中找到。当且仅当在任何元素中找不到ID时,有没有办法分析数组的每个元素并产生错误消息?
答案 0 :(得分:1)
你绝对应该读一本书如何用Java编程。 下面的所有代码都应该重写,但我留下来了解错误。
public static void updateTitle(Employee searchArray[]) {
String searchID;
Scanner input = new Scanner(System.in);
System.out.println("Enter Employee ID for manipulation: ");
searchID = input.nextLine();
Employee found = null;
for (int i = 0; i < searchArray.length; i++) {
String arrayID = searchArray[i].getEmployeeNumber();
if (searchID.equals(arrayID)) {
found = searchArray[i];
break;
}
}
if (found != null) {
System.out.println("Employee: " + searchID + " found!");
System.out.println("Employee " + searchID + "'s current title is: " + found.getEmployeeTitle());
System.out.println(" ");
System.out.println("Would you like to change this employees title? (Y/N)");
System.out.println(" ");
String answer = input.nextLine();
if (answer.equalsIgnoreCase("Y")) {
System.out.println("Enter new title: ");
String newTitle = input.nextLine();
found.setEmployeeTitle(newTitle);
found.updateTitle(newTitle);
}
} else {
System.out.println("Please enter a valid ID!");
}
}