为什么这个 If 语句不能正确地将存储的变量与数组中的元素进行比较?
所以我只是在学习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);
}
}
passwords[y]和newpass都是完全相同的字符串,当我尝试时:
if(passwords [y]=="passw0rd");
(显然选择“John”)它确实有效,所以我希望有人可以解释其中的差异以及如何解决它,以便更好地接受用户输入。
另外,我将采用 for 循环作为答案,但我希望我可以避免它。
So i'm just doing some elementary testing while I learn java, and i'm curious why this doesn't work:
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);
}
}
Both passwords[y] and newpass are the exact same string, and when I try:
if(passwords[y]=="passw0rd");
(And obviously pick the 'John') it does work, so i'm hoping someone can explain the difference and how to get around it so as to better accept user input.
Also i'll take a for loop as an answer, but i'm hoping I can avoid it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
切勿使用 == 来比较字符串。始终使用 equals 或 equalsIgnoreCase 方法。 == 将检查指向同一对象的两个引用,而 equals 将检查字符串的内容。
never use == to compare strings. Always use equals or equalsIgnoreCase methods. == will check both references pointing to the same object and equals will check the content of the strings.
使用 等于< /a> 或 compareTo 方法来比较两个字符串,而不是比较引用的
==
。输出:
Use equals or compareTo method to compare to two Strings instead of
==
which compares reference.Output: