本文介绍了为什么不= =在字符串上工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始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)函数来比较字符串,而不是 == operator。

Use the String.equals(String otherString) function to compare strings, not the == operator.

这是因为 == 运算符仅比较对象引用,而
String.equals()方法比较 String 's值,即组成每个 String 的字符序列。

This is because the == operator only compares object references, whilethe 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")){

}

或与comapre无论如何

or to comapre with regardless of case

if(gender.equalsIgnoreCase("boy")){

}

和null安全

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); // true

这篇关于为什么不= =在字符串上工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-02 01:09