2011-10-29 45 views
3

我使用if(pause == null)來做些什麼,當pausenull。但我得到的錯誤if(pause == null){does not work

the operator == is undefined for the argument type(s) long,null

下面是代碼,

public class Timer extends CountDownTimer { 
    long pause = (Long) null; 

    public Timer(long startTime, long interval) { 
     super(startTime, interval); 
    } 

    @Override 
    public void onTick(long millisUntilFinished) { 
     content.setText("Tijd over: " + millisUntilFinished/100); 
    } 

    public void onPause(long millisUntilFinished) { 
     if(pause == null) { 
      pause = millisUntilFinished; 
      content.setText("Tijd over: " + millisUntilFinished/100); 
      this.cancel(); 
     } 
     else { 
      this.start(); 
     } 
    } 

    @Override 
    public void onFinish() { 
     content.setText("Tijd is op!"); 
    } 
} 

此類沒有完成,所以忽略了代碼的其餘部分。

+0

嘗試使用「長暫停」而不是「長暫停」。 – str

+1

爲什麼你複雜的東西,只是使用,長暫停= 0;然後當你測試測試if(pause == 0){...} else {...} – Houcine

回答

3

可變pauselong,所以pause永遠不能null,且編譯器混淆。要麼使其成爲Long,要麼使用某些無效指標。

7
long pause = (Long) null; 

應該是

Long pause = null; 
^ 

long原始類型Longlong類型的包裝對象

您可以使用哨點值,而不是將其包裝爲對象。

long pause = -1; 
... 
if(pause == -1) { 
    //do something 
} 
+1

作爲對_long pause =(Long)null; _的額外評論,運行它會很有趣。由於自動拆箱,你會得到一個NullPointerException異常:) – extraneon

+0

如果我這樣做,我有另一個錯誤。 –

+0

@extraneon:是的。 –

1

long是簡單類型,它不是一個class類型,因此pause不是一個「參考」的一個對象,這意味着它不能null。如果您想要知道計時器何時暫停,請添加標誌變量;一個boolean

你可以改變longLong但似乎沒有必要,你的代碼可能是這樣的,並利用boolean

public class Timer extends CountDownTimer { 
    boolean isPaused = true; 
    long pause = 0; // not sure what this is meant to store 

    public Timer(long startTime, long interval) { 
     super(startTime, interval); 
    } 

    @Override 
    public void onTick(long millisUntilFinished) { 
     content.setText("Tijd over: " + millisUntilFinished/100); 
    } 

    public void onPause(long millisUntilFinished) { 
     if(!isPaused) { 
      isPaused = true; 
      pause = millisUntilFinished; // don't know what this is for 
      content.setText("Tijd over: " + millisUntilFinished/100); 
      this.cancel(); 
      } 
     else { 
      this.start(); 
      isPaused = false; 
     } 
    } 

    @Override 
    public void onFinish() { 
     content.setText("Tijd is op!"); 
    } 
} 
4

long是原始的。它不能爲空。只有對象引用可以。如果你真的想要爲數字使用空值,請將類型從'long'更改爲Long

1

java語言不支持C#可以使用的基本類型的可空版本的概念(請參閱How to present the nullable primitive type int in Java?上的這個問題)。因此,您必須使用Long類包裝,而不是long基元類型。

public class Timer extends CountDownTimer { 
    Long pause = null; 

    // Rest of the code ... 
} 

這將產生成本,因爲每次訪問或更新java運行時都必須打開並取消您的值。根據代碼的用途,這可能會降低應用程序的性能。這將需要分析。

另一種選擇是使用「不可能」的值來表示未初始化的pause字段。如果您知道pause將始終爲正,那麼您可以使用-1來表示未初始化的字段。