【问题标题】:If statement doesn't work, the program enters directly the "else" statement [duplicate]if语句不起作用,程序直接进入“else”语句[重复]
【发布时间】:2017-06-04 12:25:51
【问题描述】:

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

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;

        }

    }
}

【问题讨论】:

  • 或使用int 而不是Integer
  • 好吧...它解决了,谢谢先生!

标签: java if-statement mouseover


【解决方案1】:

If 正在工作,但您的状况总是得到false,因为您使用的是Integer 而不是原始的int。请注意,当您使用 Object 时,请将它们与 .equals() 方法而不是 == 进行比较。

因此:

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

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

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

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

【讨论】:

  • 使用 .equals 代替 == 就足够了,为此目的使用 int 可能会更好。非常感谢你 ! :)
  • 刚刚做到了! :)
【解决方案2】:

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

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

您要做的是比较这两个对象中的值。为此,您需要使用如下方式:

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

包装器/覆盖类:

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

示例:

Integer - int
Double - double

【讨论】:

    猜你喜欢
    • 2022-11-15
    • 1970-01-01
    • 2018-01-11
    • 2020-04-29
    • 2023-03-13
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多