2014-01-25 53 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)