2013-03-13 128 views
0

我正在開發一個使用swing表來存儲數據的eclipse中的定時器應用程序。 我遇到的主要問題是,如果if語句保持返回true,即使這些變量中的值相同(如輸出所示)。什麼可能導致這個?爲什麼如果語句返回真?

這是我的代碼片斷:

String currentPID = lblCurrentPID.getText(); 
for (int i = 0; i < tableActive.getRowCount(); i++) { 
    String currentValue = (String) tableActive.getValueAt(i, 2); 
    System.out.println(i + ": Current Value: " + currentValue + " - Current PID: "+ currentPID); 
    if (currentPID != currentValue) { 
     System.out.println("The value and PID are not the same for some reason!"); 
    } 
    else { 
     tableActive.setValueAt(ts1.getOverallTotalTime(), i, 3); 
     System.out.println(i + ": Row Was Changed!"); 
    } 
} 

這裏是輸出:

0:當前值:Test3的 - 當前PID:Test3的

值和PID是不一樣的因爲某些原因!

1:當前值:12345 - 當前PID:Test3的

價值和PID是不是出於某種原因一樣!

2:當前值:54321 - 當前PID:Test3的

價值和PID是不是出於某種原因一樣!

+1

嘗試'!currentPID.equals(currentValue)'。 – OldCurmudgeon 2013-03-13 14:43:17

回答

4
if (currentPID != currentValue){ 

應該

if (!currentPID.equals(currentValue)){ 

使用equals()檢查字符串平等。 ==運算符僅檢查兩個ref varibales是否引用同一個String對象。

+0

完整的腦屁,感謝大家的幫助! – Evidencex 2013-03-13 14:58:37

1

當你做String(或)Object比較,最好是使用equals()

if (!currentPID.equals(currentValue)){ 
+0

我不同意在所有情況下對所有對象使用equals總是更好。有時候,如果有人正在處理相同的實例或不同的實例,那麼這很重要這就是爲什麼,例如,有一個IdentityHashMap。 – 2013-03-13 15:00:41

+0

@PatriciaShanahan:同意你的意見。更新答案,始終刪除。 – kosa 2013-03-13 15:02:40

1

應該if (!currentPID.equals(currentValue))

相關問題