2014-01-25 51 views
1

謝謝你們,並且出現了新的問題。Java - While循環不起作用後的IF語句

即使列表和用戶輸入的是正確的,它仍然會打印出來,我已經發現了這個問題"Your movie or/and theatre cannot be found."

的事情。當列表(電影0-1項目&影院0-1項目)中有1個項目時,它不會打印出來"Your movie or/and theatre cannot be found."

但是,當其中有1個項目(電影1件&影院2或影院2 &影院1),它會打印出if(found == false)聲明。

public void addScreening(){ 
    System.out.println("-ADD NEW SCREENING-"); 
    String mTitle = Helper.readString("Enter movie title > "); 
    String tName = Helper.readString("Enter theatre name > "); 

    boolean found = true; 

    while(found == true){ 
    for (int i = 0; i < movies.size(); i++) { 
     for (int j = 0; j < theatres.size(); j++) { 
      if ((movies.get(i).getTitle().contains(mTitle) || mTitle.contains(movies.get(i).getTitle())) && 
        (theatres.get(j).getName().contains(tName) || tName.contains(theatres.get(j).getName()))) { 

       int year = Helper.readInt("Enter year > "); 
       int month = Helper.readInt("Enter month > "); 
       int day = Helper.readInt("Enter day > "); 
       int hour = Helper.readInt("Enter hour > "); 
       int min = Helper.readInt("Enter min > "); 

       screenings.add(new MovieScreening(Helper.thisDate(year, 
         month, day, hour, min), movies.get(i),theatres.get(j), 0)); 
       System.out.println("Added successfully"); 

     }else if((!movies.get(i).getTitle().contains(mTitle) || !mTitle.contains(movies.get(i).getTitle())) 
       || (!theatres.get(j).getName().contains(tName) || !tName.contains(theatres.get(j).getName()))){ 

     found = false; 

    } 
     } 

    }break; 
    }if (found == false){ 
    System.out.println("Your movie or/and theatre cannot be found."); 
    found = true; 
    } 
} 

輸出

-ADD NEW SCREENING- 
Enter movie title > 3 
Enter theatre name > 3 
Enter year > 3 
Enter month > 3 
Enter day > 3 
Enter hour > 3 
Enter min > 3 
Added successfully 
Your movie or/and theatre cannot be found. 
+7

'如果(發現==假)',甚至更好'如果(!找到)'' –

+3

='受讓人,''==如果進行比較(發現= FALSE)'應該是'。 –

+0

切勿將布爾值與「true」或「false」進行比較。按原樣使用它。 –

回答

2

改變這一點:

if (found = false){ 

這樣:

if (found == false){ 
+0

不,將它改爲'if(!found){'。比較布爾值爲「true」還是「false」總是要求麻煩。 –

+0

是什麼?這是荒謬的。與==相比,false不是負邏輯。 –

+0

這是多餘的,正如你從帖子中看到的那樣,增加了錯誤的可能性。在將零視爲false和非零視爲true的語言中,像if(var == true)這樣的比較傾向於產生難以檢測的意外行爲。最好是將布爾值與「true」或「false」比較。如果您絕對因爲某些尚未確診的精神疾病而必須這樣做,請通過使用尤達條件來保護自己免受錯誤的傷害。 –

3

簡單地改變

if (found = false) 

if (found == false) 

//OR 

if (!found) 

您使用賦值運算符(=),而不是比較(==)。這是一種常見的錯字,在許多情況下,使用這些格式是最容易的。

if (found) {} // if (found == true) 
if (!found) {} // if (found == false)