为什么这个 If 语句不能正确地将存储的变量与数组中的元素进行比较?

Why doesn't this If statement properly compare the stored variable with an element in an array?

所以我只是在学习的同时做一些基本测试 java,我很好奇为什么这不起作用:

public static void main(String[] args) {
        String[] names={"John","Mark","Suzy","Anthony"};
        String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
        System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
        Scanner x=new Scanner(System.in);
        int y=x.nextInt()-1;
        System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
        Scanner a=new Scanner(System.in);
        String newpass=a.nextLine();
        System.out.println(passwords[y]);
        if(passwords[y]==newpass){
            System.out.print("Hello "+names[y]+"!");
        }else{
            System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
        }
    }

密码[y] 和 newpass 是完全相同的字符串,当我尝试时:

if(passwords[y]=="passw0rd");

(显然选择 'John')它确实有效,所以我希望有人可以解释差异以及如何解决它以便更好地接受用户输入。

另外我会用一个for循环作为答案,但我希望我能避免它。

永远不要使用 == 来比较字符串。始终使用 equals 或 equalsIgnoreCase 方法。 == 将检查指向同一对象的两个引用,而 equals 将检查字符串的内容。

使用 equals or compareTo 方法比较两个字符串而不是 == 比较 reference.

import java.util.*;

public class Password{
    public static void main(String[] args) {
        String[] names={"John","Mark","Suzy","Anthony"};
        String[] passwords={"passw0rd","CandyC4ne","x5021","ADawg55"};
        System.out.println("Please indicate which user you would like to log in as:\n(1)John\n(2)Mark\n(3)Suzy\n(4)Anthony");
        Scanner x=new Scanner(System.in);
        int y=x.nextInt()-1;
        System.out.print("Please enter the password to log into "+names[y]+"'s account: ");
        Scanner a=new Scanner(System.in);
        String newpass=a.nextLine();
        System.out.println(passwords[y]);
        if(passwords[y].equals(newpass)){
            System.out.print("Hello "+names[y]+"!");
        }else{
            System.out.println("Incorrect Password. "+passwords[y]+" "+newpass);
        }
    }
}

输出:

$ javac Password.java && java Password 
Please indicate which user you would like to log in as:
(1)John
(2)Mark
(3)Suzy
(4)Anthony
1
Please enter the password to log into John's account: passw0rd
passw0rd
Hello John!