-2

I am using a while loop and an if loop to determine a response and action. For some odd reason it continues to ignore my if statements.

            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;
            }

Could someone explain what is happening and why it is failing to check the if statements. I've tried scan.nextLine as well. This problem even persisted when I removed of the toLowerCase as it was brought to my attention that it can have an affect on string values, though I did try Locale.English.

Any suggestions?

4

2 回答 2

3

Compare Strings with .equals() not == in your if statements:

if (answer.equals("yes")){
            System.out.println("Reached1");
            _exit = true;
        }
        if (answer.equals("no")){
            System.out.println("Reached1");
            exit = _exit = true;
        }
于 2013-07-17T19:11:05.013 回答
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()(单个指针比较而不是循环)便宜得多,因此,在它适用的情况下(即您可以保证您只处理内部字符串)它可以带来重要的性能改进. 但是,这些情况很少见。

资料来源:如何比较 Java 中的字符串?

于 2013-07-17T19:13:28.923 回答