2014-01-24 133 views
-1

我一直在試圖調試此代碼,但似乎無法弄清楚爲什麼即使條件已滿足(例如findTitle.equals(title));它仍然移動到'其他'條件。一切看起來很簡單,看起來是正確的。對此有何見解?'if'語句的問題

private void addNewMs() { 
    // TODO Auto-generated method stub 
    String title = Helper.readString("Enter movie title > "); 
    String theatre = Helper.readString("Enter theatre name > "); 
    Theatre Art = null; 


     for (int i = 0; i < movies.size(); i++){ 
      String findTitle = movies.get(i).getTitle(); 
      if (findTitle.equals(title)){ 
       for (int a = 0; a < theatres.size();a++){ 
        String findTheatre = theatres.get(a).getName(); 
        if (findTheatre.equals(theatre)){ 
         Art = theatres.get(a); 
         Movie m = movies.get(i); 
         int year = Helper.readInt("Enter year > "); 
         int month = Helper.readInt("Enter month > "); 
         int day = Helper.readInt("Enter day > "); 
         int hours = Helper.readInt("Enter hour > "); 
         int mins = Helper.readInt("Enter mins > "); 
         Date d = Helper.thisDate(year, month, day, hours, mins); 
         MovieScreening newScreening = new MovieScreening(d, m, Art, 0); 
         screenings.add(newScreening); 
         System.out.println("Added Successfully."); 
        } 
        else { 
         System.out.println("Movie and/or Theatre not found."); 
         break; 
        } 
       } 
      } else { 
       System.out.println("Movie and/or Theatre not found."); 
       break; 

      } 
     } 

} 
+2

打印出'findTheatre'和'theatre'的值。 –

+1

http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html - 將你的代碼拆分成更小的塊和方法,我敢打賭你發現了這個問題。 –

+0

給了我們和你輸入的例子 – kai

回答

5

您在循環中使用else子句,因此每次考慮電影或劇場與您輸入的內容都不相同時,它會執行。而是使用標誌來指示電影和劇院被找到,如果沒有設置,則在退出整個for循環時提供狀態消息:

boolean found = false; 
for (...) { 
    if (movie ...) { 
     if (theatre ...) { 
      found = true; 
     } 
    } 
} 
if (!found) { 
    System.out.println("Movie ..."); 
} 
+1

+1實際閱讀代碼並思考它應該做什麼。 –