有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java为什么这个If语句返回True?

我正在使用swing表在eclipse中开发一个计时器应用程序来存储数据。 我遇到的主要问题是,即使这些变量中的值相同(如输出所示),if语句仍会返回true。这可能是什么原因造成的

以下是我的代码片段:

String currentPID = lblCurrentPID.getText();
for (int i = 0; i < tableActive.getRowCount(); i++) {
    String currentValue = (String) tableActive.getValueAt(i, 2);
    System.out.println(i + ": Current Value: " + currentValue + " - Current PID: "+ currentPID);
    if (currentPID != currentValue) {
        System.out.println("The value and PID are not the same for some reason!");
    }
    else {
        tableActive.setValueAt(ts1.getOverallTotalTime(), i, 3);
        System.out.println(i + ": Row Was Changed!");
    }
}

以下是输出:

0:当前值:Test3-当前PID:Test3

由于某些原因,该值和PID不相同

1:当前值:12345-当前PID:Test3

由于某些原因,该值和PID不相同

2:当前值:54321-当前PID:Test3

由于某些原因,该值和PID不相同


共 (4) 个答案

  1. # 1 楼答案

    应该是if (!currentPID.equals(currentValue))

  2. # 2 楼答案

    当您进行String(或Object比较时,最好使用equals()

     if (!currentPID.equals(currentValue)){
    
  3. # 3 楼答案

     if (currentPID != currentValue){
    

    应该是

     if (!currentPID.equals(currentValue)){
    

    使用equals()检查字符串是否相等==运算符仅检查两个ref变量是否引用同一字符串对象

  4. # 4 楼答案

    为了比较java中的字符串,请使用equals==(或!=)来获取所有好的理由