2013-11-22 93 views
-1
for (int i = 0; i< expArray.length; i++){ 
      System.out.println(expArray[i]); 
      if (expArray[i] == "5"){ ///WHY IS THIS NOT WORKING!!!??    
       System.out.println("here"); 

我知道System.out...的輸出:如果塊無法識別字符串

0 
= 
0 
+ 
5 

這是我String陣列是怎麼做的:

for (int i = 0; i< expArray.length; i++){ 
     if(varTable.get(expArray[i]) != null){ 
      expArray[i] = Integer.toString((int) varTable.get(expArray[i])); 
     } 
    } 

所以,問題是,在expArray[i] == "5")如果阻止在它應該在的位置不在i=1。任何理由/想法?

+0

說明可能有幫助:爲什麼不==對字符串的工作(HTTP://計算器。 COM /問題/ 17443201 /爲什麼 - 犯規 - 工作在串/ 17443215#17443215) –

回答

5

使用nullsafe檢查,如果你有一個恆定的

if("5".equals(expArray[i])) 
4
Use .equals() instead of == for String comparison! 

==如果兩個引用指向同一對象或沒有這不是你的情況進行比較。 .equals()檢查實際的String內容。

有關字符串比較的詳細說明,請查看此SO answer

3

應該使用equals代替==

if(expArray[i].equals("5")) 
2

==是壞的比較字符串(任何物體真的,除非你知道他們是典型)。 ==只是比較對象引用。 .equals()測試相等性。對於字符串,它們通常會是相同的,但是您發現它並不能保證。

在Java中,新手遇到的最常見錯誤之一是使用==來比較字符串。您必須記住,==比較了對象引用,而不是內容。

因此,使用if(expArray[i].equals("5")