2017-06-04 52 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