java - 为什么我的 equals 方法在这个类中不起作用?它无法正常运行

标签 java string comparison

基本上,如果他们已经将该人添加到 ArrayList,我希望它停止并打印一条消息,但它不会这样做。

方法如下:

@Override
    public boolean equals(Object o) {
        if (this.name == ((Student)o).getName() && this.ID == ((Student)o).getID()) {
            return true;
        }
        else {
            return false;
        }
    }

以及它所使用的代码部分:

public void addStudents() {
        Scanner keyboard = new Scanner(System.in);
        String name = "", ID = "";

        System.out.println("Welcome! Please type exit at any point to stop entering students and for the lottery to commence.\n");

        System.out.print("Student name: ");
        name = keyboard.nextLine();

        if (!name.equals("exit")) {
            System.out.print("Student ID: ");
            ID = keyboard.nextLine();
        }

        while (!name.equals("exit") && !ID.equals("exit")) {
            System.out.print("\nStudent name: ");
            name = keyboard.nextLine();

            if (!name.equals("exit")) {
                System.out.print("Student ID: ");
                ID = keyboard.nextLine();

                if (!ID.equals("exit")) {
                    boolean contains = false;

                    for (int i = 0; i < students.size(); i++) {
                        if (students.get(i).equals((new Student(name, ID)))) {
                            contains = true;
                        }
                    }

                    if (!contains) {
                        students.add(new Student(name, ID));
                    }
                    else {
                        System.out.println("You can only enter once.");
                    }
                }
            }
        }
    }

我已经为此付出了相当长的一段时间,但无法弄清楚为什么它不起作用。

最佳答案

使用equals()方法比较字符串,而不是==

关于java - 为什么我的 equals 方法在这个类中不起作用?它无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12763269/

相关文章:

java - servlet 发生异常时如何重定向到错误页面?

string - 从python中的字符串中搜索字符序列

arrays - 找到用户坐标和坐标数组之间最近的位置

PHP 比较 2 个数组的值是否存在

java - 如何解析计算器输入字符串

javascript - JQuery:比较两个多行字符串,一个从 HTML 中提取 - 不起作用?

java - 检索项目 : No resource found that matches the given name android 的父级时出错

java - 当使用 JSTL forEach 时,数组打印 String.toString() 而不是实际的字符串值

java - GWT 资源包找不到类路径

c - "Wrapping"一个 C 字符数组,每 x 个字符放入 '\n'——strcat 问题