Java While循环问题
我使用while循环和if循环来确定响应和操作。出于某种奇怪的原因,它继续忽略我的if语句Java While循环问题,java,if-statement,while-loop,Java,If Statement,While Loop,我使用while循环和if循环来确定响应和操作。出于某种奇怪的原因,它继续忽略我的if语句 Boolean _exit = false; while (_exit == false){ System.out.println("\nWould you like another meal?\tYes or No?"); String answer = scan.next().toLowerCase();
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语句吗。我也试过扫描下一行。当我删除toLowerCase时,这个问题仍然存在,因为我注意到它会对字符串值产生影响,尽管我尝试了Locale.English
有什么建议吗?在if语句中将字符串与.equals()而不是==进行比较:
if (answer.equals("yes")){
System.out.println("Reached1");
_exit = true;
}
if (answer.equals("no")){
System.out.println("Reached1");
exit = _exit = true;
}
从另一个线程:
=
测试引用相等性
.equals()
测试值是否相等
因此,如果确实要测试两个字符串是否具有相同的值,则应使用.equals()
(除非在少数情况下,您可以保证具有相同值的两个字符串将由相同的对象表示,例如:)
=
用于测试两个字符串是否为同一对象
需要注意的是,=
比equals()
便宜得多(单指针比较而不是循环),因此,在适用的情况下(即,您可以保证只处理内部字符串),它可以提供重要的性能改进。然而,这种情况很少见
来源:不要将
字符串
值与=
进行比较;与equals
方法相比。顺便说一句,在你的第二个if条件中退出
是什么,它应该是else if
。
// 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