字符串answer1 =“是”; if(answer1 ==“yes”)给出错误。为什么?

时间:2013-10-09 20:24:56

标签: java

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);

        System.out.println("Enter your name");
        String name = scanner.nextLine();
        System.out.println("Is "+ name + " really your name?");
        String answer1 = scanner.nextLine();
        if (answer1 == "yes"){
        System.out.println("Alright ");
        }else  {System.out.println("Liar!");
    }
    }
}

即使我输入了Liar!,它也会输出yes,因此answer1等于yes。为什么呢?

1 个答案:

答案 0 :(得分:4)

因为使用==您正在测试引用相等性,而不是值相等性。 Good reading.

取而代之的是answer1 == "yes" answer1.equals("yes")