加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么不= =在String上工作?

发布时间:2020-12-15 02:05:30 所属栏目:Java 来源:网络整理
导读:参见英文答案 How do I compare strings in Java?????????????????????????????????????23个 我刚刚开始Java编程.我到目前为止都很喜欢它,但我一直坚持这个问题. 当我运行此代码时,每当我输入“boy”时,它只会响应GIRL: import java.util.Scanner;public cl
参见英文答案 > How do I compare strings in Java?????????????????????????????????????23个
我刚刚开始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"); 
        }
    }
}

为什么?

解决方法

使用String.equals(String otherString)函数来比较字符串,而不是==运算符.

这是因为==运算符只比较对象引用
String.equals()方法比较两个String的值,即构成每个String的字符序列.

equals() method from Source code of 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")){

}

无论如何,或与comapre

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); //真正

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读