1

对不起,如果我的问题似乎有点模糊。

基本上我要做的是在构造函数对象上使用字符串比较进行错误检查,该构造函数对象存储在数组中。我认为我的想法是正确的:(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!");
        }

    }
}

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

4

1 回答 1

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!");
    }
}
于 2013-09-17T19:24:14.383 回答