-3
String firstanswer = scan.nextLine();
    if(firstanswer == answer2)
        {
            System.out.println("OK lets get started");
            }
    else
        {
            System.out.println("That is incorrect, of course you want to play");
            }

//answer2 设置为“是”,我在上面声明了它

4

3 回答 3

7

制作它firstanswer.equals(answer2)而不是firstanswer == answer2.

当您想检查Stringjava 中的相等性时,请使用equals方法而不是==运算符。

  • equals方法检查String对象的内容是否相同
  • ==运算符检查两个引用变量是否引用同一个String对象

要了解字符串和相等,请阅读String comparison with equals and assignment operator它将帮助您更好地理解这个概念。

于 2013-10-03T12:11:17.277 回答
1

Use equals() instead of == to compare strings.

于 2013-10-03T12:12:23.933 回答
1

if(firstanswer.equals(answer2)) is what you're looking for.

firstanswer and answer2 are pointers to string objects. == checks to see whether the pointers are equal (whether they point to the same object), while equals() compares the contents of the two strings and returns a boolean representing whether or not the contents are equal.

于 2013-10-03T12:12:35.883 回答