gpt4 book ai didi

java - 通过在遍历数组时比较字符串来验证有效性

转载 作者:行者123 更新时间:2023-11-30 11:28:28 25 4
gpt4 key购买 nike

抱歉,如果我的问题看起来有点含糊。

基本上,我要做的是对存储在数组中的构造函数对象使用字符串比较进行错误检查。我想我的想法是正确的:(Count 是一个静态整数,每当在另一个方法中添加员工时它就会迭代)

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!");
}

}
}

这成功地进行了错误检查,但是因为它正在遍历数组,所以如果数组元素 > 0 并且在数组中找到,它将在验证消息之前显示错误消息。有什么方法可以分析数组的每个元素并在且仅当在任何 元素中找不到 ID 时才生成错误消息?

最佳答案

您绝对应该阅读一本如何使用 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!");
}
}

关于java - 通过在遍历数组时比较字符串来验证有效性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18838962/

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