2013-07-17 280 views
-2

我正在使用while循环和if循环来确定响应和操作。由于某些奇怪的原因,它继续忽略我的if语句。Java while循环问题

  Boolean _exit = false; 
     while (_exit == false){ 
      System.out.println("\nWould you like another meal?\tYes or No?"); 
      String answer = scan.next().toLowerCase(); 
      if (answer == "yes"){ 
       System.out.println("Reached1"); 
       _exit = true; 
      } 
      if (answer == "no"){ 
       System.out.println("Reached1"); 
       exit = _exit = true; 
      } 

有人可以解释发生了什么,为什么它没有检查if语句。我也试过scan.nextLine。当我移除toLowerCase时,这个问题甚至持续存在,因为它引起了我的注意,它可能对字符串值产生影响,尽管我尝试了Locale.English。

有什么建议吗?

+3

不要拿'String'值与''==;与“equals”方法比较。 – rgettman

+0

顺便说一下,在第二个if条件中'exit'是什么,它应该是一个'else if'。 –

回答

3

比较.equals字符串()在你的if语句不==:

if (answer.equals("yes")){ 
      System.out.println("Reached1"); 
      _exit = true; 
     } 
     if (answer.equals("no")){ 
      System.out.println("Reached1"); 
      exit = _exit = true; 
     } 
0

从其他线程:

==测试参考平等。

.equals()测试值相等。因此,如果您确实想要测试两个字符串是否具有相同的值,则应使用.equals()(除非在某些情况下,您可以保证具有相同值的两个字符串将由相同对象表示,例如:String interning )。

==用于测试两个字符串是否相同对象

// These two have the same value 
new String("test").equals("test") ==> true 

// ... but they are not the same object 
new String("test") == "test" ==> false 

// ... neither are these 
new String("test") == new String("test") ==> false 

// ... but these are because literals are interned by 
// the compiler and thus refer to the same object 
"test" == "test" ==> true 

// concatenation of string literals happens at compile time resulting in same objects 
"test" == "te" + "st" ==> true 

// but .substring() is invoked at runtime, generating distinct objects 
"test" == "!test".substring(1) ==> false 

需要注意的是==equals()(单一指针对比,而不是一个循环)便宜得多是很重要的,因此,在情况下是适用的(即你可以保证你只处理实习字符串),它可以提供重要的性能改进。 但是,这些情况很少见。

来源:How do I compare strings in Java?