包含字符串的变量失败==使用“相同”字符串进行测试。为什么?

时间:2011-10-18 01:09:11

标签: java

我是个白痴:

我的代码是下面的代码。我运行了代码,输入4作为我的答案。但是,该程序仍然告诉我答案是不正确的。我做错了什么?非常感谢你的帮助。

import java.io.*;

class class1 {

  public static void main (String[] args) throws IOException { 
    BufferedReader input = new BufferedReader (new InputStreamReader(System.in));
    System.out.println("What is the answer to 2 + 2");
    String answer;

    answer = input.readLine();

    if ( answer == "4"){
      System.out.println("Correct");
    } else System.out.println("Incorrect");

    }
  }
}

3 个答案:

答案 0 :(得分:7)

您无法使用==比较字符串。你需要这样做:

answer.equals("4");

原因是因为==仅在双方都是完全相同的对象(同一个实例)时才有效。你真正需要的是检查两个字符串是否具有相同的内容。

更具体地说,示例中的==会比较answer是否指向与"4"相同的对象,而不是{{1}}。

更多技术细节:http://leepoint.net/notes-java/data/expressions/22compareobjects.html

答案 1 :(得分:1)

或者如果你想进行数值比较

if(Integer.valueOf(answer) == 4)

答案 2 :(得分:0)

您需要替换

if ( answer == "4")

使用:

if (answer.equals("4"))