2014-04-13 180 views
-1

我想要發生的是要讀取文件並將文本存儲在名爲data []的字符串數組中。數據[3]應該包含「警告燈是紅色的」或「警告燈是綠色的」,並且在它被破壞並且既不包含我定義的自定義異常的情況下,我想拋出。我的代碼,如下所示:總是拋出異常

if(data[3].equals("Warning Lights are red")){ 
      //do something 
     } 
     else if(data[3].equals("Warning Lights are green")){ 
      //do something 
     } 
     else if(!data[3].equals("Warning Lights are red") && !data[3].equals("Warning Lights are green")){ 
      throw new FileCorruptionException("Unfortunately the status file was corrupted, please try printing to the file again to fix this issue."); 

     } 

,我遇到的問題是,FileCorruptionException總是被拋出,即使數據[3]確實是等於或者「警告燈是紅色的」,或「警告燈是綠色的「,我已經在文本文件中檢查以確認這一點。我懷疑我有一個邏輯錯誤,但我不知道它會是什麼。任何建議表示讚賞。

+1

也許'data [3]'不包含你認爲它的作用。你輸出它的值和它的長度來檢查? –

+2

檢查虛假的空白。 – Stewart

+0

顯然至少有一個你在問題中聲明的東西不是真的,否則你的代碼將按預期運行。您應該將其減少到[最小測試用例](http://stackoverflow.com/help/mcve)以更徹底地探究此問題。 –

回答

2

您可能會有一些空白,就像字符串末尾的新行一樣。試試這個,以檢查是否有任何空白:

System.out.print(":" + data[3] + ":") 

你可以使用String.trim除去開頭和結尾的空白:

if (data[3].trim().equals() ... 
2

這很可能是一個詞彙問題。有條件的空白和data[3]中的空白可能有所不同。在data[3]字符串中檢查紅色/綠色後的其他空白。希望這可以幫助。

編輯:如果您沒有其他情況需要考慮,也可以使用else而不是else if來拋出異常。

1

嘗試用String.equalsIgnoreCase()而不是String.equals()。可能會有一些案例問題。

因爲您已經在前兩個條件中檢查過了,所以沒有必要在最後else if處進行支票。

 if(data[3].equalsIgnoreCase("Warning Lights are red")){ 
     //do something 
    } 
    else if(data[3].equalsIgnoreCase("Warning Lights are green")){ 
     //do something 
    } 
    else{ 
     throw new FileCorruptionException("Unfortunately the status file was corrupted, please try printing to the file again to fix this issue."); 
    }