2014-09-28 28 views
1

我有點麻煩。問題是,當我試圖比較2個字符串(類型字符串)運算符'=='返回FALSE,但實際上字符串是平等的。 下面是帶有問題的代碼:錯誤的結果,而字符串比較

//before the following code I filled the "LinkedList <String> command" and there is 
//a node with value of args[0] 
String deal=""; 
Iterator it = commands.listIterator(); 
if(it.hasNext() == true) 
{ 
    if(it.next() == args[0]) 
    { 
     deal += it.next(); 
     it.hasNext(); 
     break; 
    } 
} 

謝謝!!!

回答

1

要比較兩個字符串,你應該使用方法equals()或equalsIgnoreCase()。

你的情況

if(it.next().equals(args[0])) 

操作==如果兩個對象是同一對象,在內存地址相同返回true。

+0

那不會編譯,你忘了「。」在next()和等於 – PsyCode 2014-09-28 20:39:24

+0

Oooh yes!非常感謝。我怎麼能忘記...當然我們的講師告訴我們'回合等於(...) – 2014-09-28 20:40:46

+0

@PsyCode編輯:) – Alboz 2014-09-28 20:41:21

1

比較兩個字符串時使用.equals。因此,使用

(it.next()).equals(args[0]) 
+0

我真是個假人。問題是我通常使用C/C++ =) – 2014-09-28 20:41:59

1

你必須使用.equals方法:

String deal=""; 
Iterator it = commands.listIterator(); 
if(it.hasNext() == true) 
{ 
    String next = it.next(); 
    if(next.equals(args[0])) 
    { 
     deal += next; 
     break; 
    } 
} 

要小心,一旦.next()返回值和移動內部光標移動到下一個值。

==不能用於String,因爲==如果同一對象實例位於兩側,則爲真。相同的字符串內容可以在許多String實例中。

+0

非常感謝。我剛剛忘了,因爲我用C/C++ =) – 2014-09-28 20:45:38

+0

製作程序很酷,你可以投票並接受我詳細的回答:) – 2014-09-28 20:46:39

1

有兩種比較字符串的方法。

  1. 比較字符串的值(使用.equals實現)。
  2. 比較實際對象(使用==運算符實現)。

在你的代碼是比較受it.next() & args[0]簡稱,而你應該比較使用it.next().equals(args[0])的兩個值的引用。

0

如果您使用==來比較兩個int值,那麼它會比較這兩個值,因爲int是原始數據類型。如果使用「==」比較String對象,則檢查兩個String引用是否引用相同的String對象。它不考慮String對象的值。

如果你想比較String對象的值,你必須使用String類的equals()。此方法正在比較兩個String對象的內容。