2017-06-04 51 views
0

我正在尝试编写一个检测“空闲”状态的程序,但在代码中看不到问题。有人可以帮助我请一个有用的提示?这里是我的代码:如果语句不起作用,程序直接输入“else”语句

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; 

     } 

    } 
} 
+3

或使用'int'不'Integer'。 –

+0

嗯,是的......它解决了,谢谢先生! –

回答

0

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

因此:

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

==Object.equals()方法之间的差异参见this

正如评论中所述,您可以始终使用int来达到此目的,而不是Integer

请参阅this关于Integerint之间的差异。

+0

这足以使用.equals而不是==,对于这样的目的来说int也可能更好。非常感谢你 ! :) –

+0

刚刚做到了! :) –

0

您正在比较两个对象的内存地址,即Integer对象(包装类)。

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

你想要做的是比较这两个对象中的值。要做到这一点,你需要使用如下:

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

包装/覆盖类:

  • 没有为每个基本数据类型的包装类。
  • 原始类型用于性能原因(这对您的 程序更好)。
  • 无法使用原始类型创建对象。
  • 允许创建对象和操作基本类型(即 转换类型)。

Exsample:

Integer - int 
Double - double