为什么“ if”语句在Java代码中不会返回true?

时间:2019-10-01 23:28:26

标签: java string if-statement

import java.util.*;

public class Main
{
    public static void main(String[] args) {

        boolean finished = false;
        Scanner input = new Scanner(System.in);
        String ans;

        while(finished == false)
        {
            System.out.println("Continue?(y/n): "); 
            ans = input.next();
            if (ans == "n")
            {
                finished = true;
            }
        }
    }
}

这是控制台:

Continue?(y/n):                                                                                                                                                                    
y                                                                                                                                                                                  
Continue?(y/n):                                                                                                                                                                    
y                                                                                                                                                                                  
Continue?(y/n):                                                                                                                                                                    
n                                                                                                                                                                                  
Continue?(y/n):                                                                                                                                                                    
n                                                                                                                                                                                  
Continue?(y/n):

正如预期的那样,当我输入“ n”时,if语句应返回true(并且程序应停止),但结果始终返回false。

0 个答案:

没有答案