2011-08-10 45 views
1

嗨我只是瞎搞,我不能得到這個工作:對象比較:地址VS內容

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"); 
} 

它當然應該,如果你輸入Hello打印你好你好,但它不會。我使用Eclipse只是爲了解決問題。請稍後快速幫助

回答

5

應該是if (x.equals("hello"))

使用java對象時,==用於參考比較。 .equals()進行價值比較。

+0

這很奇怪,我從來沒有這樣做與掃描儀。這是特定於Eclipse的嗎?大概愚蠢的問題... – Josh

+2

這不是「怪異」,它是事情在Java中完成的方式。它與Eclipse無關;) – Jacob

+5

或null-safe:'「hello」.equals(x)' – pmnt

1

x ==「hello」比較引用不是值,你將不得不做x.equals(「hello」)。

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> 
2

你不能比較喜歡that.Because字符串,字符串是一個class.So如果你想比較其內容使用等於

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

使用"hello".equals(x)從未相反,因爲它處理空。

3

在測試非基本類型的相等性時,不要使用==,它將測試的參考等號。改爲使用.equals(..)

請看下圖:

equals vs ==

當使用==你使用equals當你比較它們的內容比較盒,地址。

+0

價值1000字的圖片 – Nipuna

1

==運算符檢查引用(不是值)的相等性。在你的情況下,你有2個字符串類型的對象,它們具有不同的引用,但具有相同的值「你好」。 String類具有用於檢查值相等的「equals」方法。語法是if(str1.equals(str2))。

1

試試這個作爲比較:

if (x.equals("hello")) 
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是錯誤的,但他們繼續在相同的字符串中,因此equals返回true。

表達式hello == hello2是真實的,因爲Java編譯器足夠聰明,可以執行兩個字符串常量的串聯。

所以要比較String對象,必須使用equals方法。