2015-10-17 35 views
0

當計時器變爲零時,newAttempt將減1.此計時器將循環回到newAttempt變爲零。它會顯示信息消息說遊戲結束。我不知道如何循環這個。每當我運行程序時,我的電腦都會凍結。循環計時器直到newAttempt == 0

這是我的計劃:

 int delay = 1000; 
    int period = 1000; 
    timer = new Timer(); 
    interval = Integer.parseInt("10"); 
    timer.scheduleAtFixedRate(new TimerTask() { 
     public void run() { 
      do{ 
      if (interval == 1) 
       if (interval == 1) 
        timer.cancel(); 
      --interval; 
      String interv = Integer.toString(interval); 
      timerTextField.setText("0:"+interv); 
      if(interval==0){ 
       --counter; 
       newAttempt = Integer.parseInt(attemptTextField.getText()); 
       newAttempt -= 1; 
       String convert = Integer.toString(newAttempt); 
       attemptTextField.setText(convert); 
       if(counter==0) 
        interval = Integer.parseInt("10"); 
      } 
      }while(newAttempt!=0); 
     } 
    }, delay, period); 

我更新了我的代碼。這仍然是錯誤的,但我認爲我很接近。

+0

抱歉。生病改變了代碼 – Mariel

+0

但@hotzst是正確的:它不應該在循環中完成。 – RealSkeptic

+0

目前尚不清楚你試圖達到什麼目標。計時器任務中不應該有長循環。你用'interval'做什麼?爲什麼它有兩個相同的'if'條件? 'newAttempt'代表什麼?它爲什麼來自文本字段? – RealSkeptic

回答

0

不要在while循環中運行它。創建一個Timer和一個TimerTask並將任務存儲在變量中。

然後,您可以將任務發佈到計時器。當時間到了時,任務將被執行。在那裏你可以計算出你的計數器是否已經達到0,如果沒有,則向計時器添加另一個任務。

+0

是否這樣? '--counter; '然後,'如果(計數器== 0)' – Mariel

+0

你基本上已經在你的代碼中了:計數器是'newAttempt'。從上面的代碼中我可以得知,嘗試的次數可以從任務執行到下一次執行,或者'attemptTextField'是隻讀字段? – hotzst

+0

attemptTextField是一個只讀字段,但您可以更改主菜單中設置的嘗試次數。 – Mariel