2017-05-20 50 views
1

我做了幾乎所有的事情來解決惱人的問題,「龍不能被解除引用」,但任何事情都解決了。因此,任何人都可以請幫助我嗎?問題是當我檢查程序是否在if(System.currentTimeMillis().longValue()==finish)超時時,比較不起作用。長不能解除引用

public void play() 
    {    
     long begin = System.currentTimeMillis(); 
     long finish = begin + 10*1000; 

     while (found<3 && System.currentTimeMillis() < finish) { 
      Command command = parser.getCommand(); 
      processCommand(command); 
     } 
     if(System.currentTimeMillis().longValue()==finish){ 
      if(found==1){System.out.println("Time is out. You found "+found+" item.");} 
      else if(found>1 && found<3){System.out.println("Time is out. You found "+found+" items.");}} 
     else{ 
      if(found==1){System.out.println("Thank you for playing. You found "+found+" item.");} 
      else if(found>1 && found<3){System.out.println("Thank you for playing. You found "+found+" items.");} 
      else{System.out.println("Thank you for playing. Good bye.");} 
     } 
    } 
+3

有Long''之間的差異,這是一類,因而具有方法和'long',這是一個基本類型,因此沒有按」沒有辦法。 System.currentTimeMillis()返回一個long而不是Long。你在while循環中做他正確的事情,但不是在if中。所以你已經有了你的代碼的解決方案。 –

+0

我的代碼中的問題是時間限制比較不起作用。這就是在這裏發佈它的原因 –

+1

你似乎也認爲System.currentTimeMillis()在重複調用時會給你每一毫秒。它不會。調用它本身需要時間,你在while循環中的內容也是如此。時鐘的精確度通常在10毫秒左右。 –

回答

2

System.currentTimeMillis()返回一個原語long不是一個對象Long。 所以你不能調用longValue()方法或它的任何方法,因爲原語不能是方法調用的對象。

此外,調用longValue()是無用的,因爲System.currentTimeMillis()返回的值已經很長。

這是更好的:

if(System.currentTimeMillis()==finish){ 

但事實上,這個條件:if(System.currentTimeMillis()==finish)不能true即使System.currentTimeMillis() == finishwhile聲明:

while (found<3 && System.currentTimeMillis() < finish) { 
     Command command = parser.getCommand(); 
     processCommand(command); 
    } 

因爲while語句的結束和之間條件評估:

if(System.currentTimeMillis() == finish),時間goe s已經過去了。

所以,你應該寧願使用:

if(System.currentTimeMillis() >= finish){ 
+0

因此,解決方案是什麼?如何使時間比較工作? –

+0

我已經更新,解釋超出編譯錯誤的問題 – davidxxx

+0

完美!它工作順利。這是一個簡單的解決方案,真的很棒。非常感謝你。 –