if语句不行,程序直接进入"else"语句

If statement doesn't work, the program enters directly the "else" statement

我正在尝试编写一个程序来检测 "idle" 状态,但我在我的代码中没有发现问题。有人可以帮我提供一个有用的提示吗?这是我的代码:

package idlestatus;

import java.awt.MouseInfo;

public class Idlestatus {

    public static void main(String[] args) throws InterruptedException {
        Integer firstPointX = MouseInfo.getPointerInfo().getLocation().x;
        Integer firstPointY = MouseInfo.getPointerInfo().getLocation().y;
        Integer afterPointX;
        Integer afterPointY;
        while (true) {
            Thread.sleep(10000);
            afterPointX = MouseInfo.getPointerInfo().getLocation().x;
            afterPointY = MouseInfo.getPointerInfo().getLocation().y;
            if (firstPointX == afterPointX && firstPointY == afterPointY) {
                System.out.println("Idle status");
            } else {
                System.out.println("(" + firstPointX + ", " + firstPointY + ")");
            }
            firstPointX = afterPointX;
            firstPointY = afterPointY;

        }

    }
}

If 有效,但您的条件总是变得 false,因为您使用的是 Integer 而不是原始 int。请注意,当您使用 Object 时,将它们与 .equals() 方法而不是 == 进行比较。

因此:

if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY)) {
    //your code...
}

请参阅 this 以了解 ==Object.equals() 方法之间的区别。

如评论中所述,您始终可以将 int 用于此类目的,而不是 Integer

请参阅 this 以了解 Integerint 之间的区别。

您正在比较两个对象的内存地址,即 Integer object(wrapper class).

if (firstPointX == afterPointX && firstPointY == afterPointY) 

您要做的是比较这两个对象中的值。为此,您需要像下面这样使用:

if (firstPointX.equals(afterPointX) && firstPointY.equals(afterPointY))

包装器/覆盖物 classes:

  • 每种原始数据类型都有一个包装器 class。
  • 出于性能原因使用原​​始类型(这更适合您 程序)。
  • 无法使用原始类型创建对象。
  • 允许创建对象和操作基本类型(即 转换类型)。

示例:

Integer - int
Double - double