为什么 == 不适用于 String? [英] Why doesn’t == work on String?
问题描述
我刚刚开始 Java 编程.到目前为止我喜欢它,但我已经被这个问题困住了一段时间.
I just started Java programming. I love it so far, but I have been stuck on this problem for a while.
当我运行这段代码时,每当我输入boy"时,它都会回复GIRL
:
When I run this code, whenever I type in "boy" it will just respond with GIRL
:
import java.util.Scanner;
public class ifstatementgirlorboy {
public static void main(String args[]) {
System.out.println("Are you a boy or a girl?");
Scanner input = new Scanner(System.in);
String gender = input.nextLine();
if(gender=="boy") {
System.out.println("BOY");
}
else {
System.out.println("GIRL");
}
}
}
为什么?
推荐答案
使用 String.equals(String otherString)
函数来比较字符串,而不是 ==
运算符.
Use the String.equals(String otherString)
function to compare strings, not the ==
operator.
这是因为 ==
运算符只比较对象引用,而String.equals()
方法比较两个 String
的值,即组成每个 String
的字符序列.
This is because the ==
operator only compares object references, while
the String.equals()
method compares both String
's values i.e. the sequence of characters that make up each String
.
public boolean equals(Object anObject) {
1013 if (this == anObject) {
1014 return true;
1015 }
1016 if (anObject instanceof String) {
1017 String anotherString = (String)anObject;
1018 int n = count;
1019 if (n == anotherString.count) {
1020 char v1[] = value;
1021 char v2[] = anotherString.value;
1022 int i = offset;
1023 int j = anotherString.offset;
1024 while (n-- != 0) {
1025 if (v1[i++] != v2[j++])
1026 return false;
1027 }
1028 return true;
1029 }
1030 }
1031 return false;
1032 }
所以你应该写
if(gender.equals("boy")){
}
或者不分大小写
if(gender.equalsIgnoreCase("boy")){
}
为了空安全
if("boy".equals(gender)){
}
<小时>
未来参考:
String s1 = "Hello"; // String literal
String s2 = "Hello"; // String literal
String s3 = s1; // same reference
String s4 = new String("Hello"); // String object
String s5 = new String("Hello"); // String object
这里 s1 == s2 == s3 但 s4 != s5
在哪里
anyOfAbove.equals(anyOtherOfAbove);//真
这篇关于为什么 == 不适用于 String?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!