对象比较:地址与内容

时间:2011-08-10 05:45:00

标签: java

嘿伙计们,我只是乱搞,我不能让这个工作:

public static void main(String[] args){
    Scanner input = new Scanner (System.in);
    String x = "hey";
    System.out.println("What is x?:  ");
    x = input.nextLine();
    System.out.println(x);
    if (x == "hello")
        System.out.println("hello");
    else
        System.out.println("goodbye");
}

当然,如果你输入你好,它应该打印你好你好,但它不会。我正在使用Eclipse来搞砸。请快点帮忙

10 个答案:

答案 0 :(得分:5)

应为if (x.equals("hello"))

使用java对象,==用于参考比较。 .equals()用于价值比较。

答案 1 :(得分:3)

在测试非基本类型的相等性时,不要使用==,它会测试的参考相等性。请改用.equals(..)

请看下图:

equals vs ==

使用==时,您要比较这些方框的地址,在使用equals时,您需要对其内容进行比较。

答案 2 :(得分:2)

你无法比较那样的字符串。因为String是一个类。所以如果要比较它的内容,请使用equals

 if (x.equals("hello"))
        System.out.println("hello");
    else
        System.out.println("goodbye");

答案 3 :(得分:1)

x ==“hello”比较引用而不是值,你必须做x.equals(“hello”)。

答案 4 :(得分:1)

String s = "something", t = "maybe something else";
    if (s == t)      // Legal, but usually WRONG.
    if (s.equals(t)) // RIGHT
    if (s > t)    // ILLEGAL
    if (s.compareTo(t) > 0) // CORRECT>

答案 5 :(得分:1)

使用"hello".equals(x)从不反向,因为处理null。

答案 6 :(得分:1)

==运算符检查引用的相等性(不是值)。在您的情况下,您有2个String类型对象,它具有不同的引用但具有相同的值“hello”。 String类具有用于检查值相等性的“equals”方法。语法为if(str1.equals(str2))。

答案 7 :(得分:1)

尝试此作为比较:

if (x.equals("hello"))

答案 8 :(得分:0)

答案 9 :(得分:0)

参加此示例程序:

public class StringComparison {
    public static void main(String[] args) {
        String hello = "hello";
        System.out.println(hello == "hello");

        String hello2 = "hel" + "lo";
        System.out.println(hello == hello2);

        String hello3 = new String(hello);
        System.out.println(hello == hello3);
        System.out.println(hello3.equals(hello));
    }
}

它的输出是:

true
true
false
true

对象hellohello3具有不同的引用,这就是为什么hello == hello3为false,但它们包含相同的字符串,因此equals返回true。

表达式hello == hello2是正确的,因为Java编译器足够聪明,可以执行两个字符串常量的连接。

因此,要比较String对象,您必须使用equals方法。

相关问题