2013-10-15 30 views
3

我正在使用foreach循環來運行arraylist並將名稱與字符串進行比較。但是我不知道爲什麼當我比較一個字符串的名字時總會打印出來。嘗試按名稱調用arraylist中的項目。我不知道爲什麼這不起作用 - 家庭作業

for (Picture item : collection) { 


       System.out.println("This is the label " + item.getName()); 

       if (item.getName().equals("This shouldn't work")); { 

       System.out.println("Why is this working"); 

       } 
      } 
     } 

輸出

getting the name test A 
This is the label A 
getting the name test A 
Why is this working 
getting the name test B 
This is the label B 
getting the name test B 
Why is this working 
+7

你的'if'條件後面有一個懸掛';'。 –

+0

@SotiriosDelimanolis常見的分號用法/非用法問題。 –

+0

還有那個'呃'的臉掌...快速調查,你輸了多少個小時,@pplll,你會再次這樣做嗎? (哦,對我來說,它是大約2,並且再也沒有這樣做過)...... – rolfl

回答

4

分號表示語句,這是塊的一個組成部分的結束。通過鍵入

if (condition); 
{ 
    System.out.println("Why is this working"); 
} 

要表示

if (condition) 
    // empty statement 
; 
{ // unconditional opening of a block scope 
    System.out.println("Why is this working"); 
} 

因此,如果您if語句判斷爲真,什麼也不會發生,如果評估不實,則空語句將被跳過,這是相當於到沒有發生。

現在,如果你已經刪除了分號,那麼接下來的「聲明」將是一個塊範圍的開口:

if (condition) { 
    // conditional opening of a block scope 
    System.out.println("Why is this working"); 
} 

,你會看到預期的行爲,跳過「爲什麼這工作「作爲條件爲假時的輸出。

+1

像這樣的情況幾乎足以希望獲得所有空語句所需的「空語句」關鍵字。 'if(condition)empty_stmt' –

1

if (item.getName().equals("This shouldn't work")); //這裏分號目前

您的代碼應該如下喜歡

if (item.getName().equals("This shouldn't work")){ 

} 
+0

這會更好地解釋爲什麼在使用分號時這不起作用 –

0

變化

if (item.getName().equals("This shouldn't work")); { 

if (item.getName().equals("This shouldn't work")) { 

如果你把分號if語句結束

相關問題