我刚刚开始Java编程.我到目前为止都很喜欢它,但我一直坚持这个问题.
当我运行此代码时,每当我输入"boy"时,它只会响应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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么?
Sur*_*tta 21
使用该String.equals(String otherString)
函数比较字符串,而不是==
运算符.
这是因为==
操作符仅比较对象引用,而该String.equals()
方法比较两个String
值,即组成每个值的字符序列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 }
Run Code Online (Sandbox Code Playgroud)
所以你应该写
if(gender.equals("boy")){
}
Run Code Online (Sandbox Code Playgroud)
无论如何,或与comapre
if(gender.equalsIgnoreCase("boy")){
}
Run Code Online (Sandbox Code Playgroud)
并且为了安全
if("boy".equals(gender)){
}
Run Code Online (Sandbox Code Playgroud)
以后的参考:
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
Run Code Online (Sandbox Code Playgroud)
这里 s1 == s2 == s3 but s4 != s5
在哪里
anyOfAbove.equals(anyOtherOfAbove); //true
比较类型的对象时String
,应使用equals
方法而不是运算符==
. equals
将String
在==
检查时比较对象的值,以查看它们是否是内存中的同一对象.
所以代替:
if(gender=="boy")
Run Code Online (Sandbox Code Playgroud)
使用
if(gender.equals("boy"))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12413 次 |
最近记录: |