Java TimeUnit错误

时间:2015-04-24 11:54:45

标签: java exception time jbutton

我想用Numberfields和一个按钮创建一个Java程序。 单击按钮时,它等待和放在Numberfield中的时间。整数工作正常,但该功能不起作用。

以下是代码:

public void jButton1_ActionPerformed(ActionEvent evt) {
    sekunden = Integer.parseInt(jNumberField3.getText()); 
    minuten = Integer.parseInt(jNumberField2.getText());
    stunden = Integer.parseInt(jNumberField1.getText());
    zeit = sekunden + minuten*60 + stunden*60*60;//berechnet die zeit in sekunden
    TimeUnit.SECONDS.sleep(zeit);//here is the error
    System.out.println("zeit");
} // end of jButton1_ActionPerformed

错误消息如下所示:

ES.java:78:27: error: unreported exception InterruptedException; must be caught or declared to be thrown TimeUnit.SECONDS.sleep(zeit);

2 个答案:

答案 0 :(得分:1)

方法调用TimeUnit.SECONDS.sleep(zeit)抛出必须被捕获的InterruptedException

public void jButton1_ActionPerformed(ActionEvent evt) {
   try {
    sekunden = Integer.parseInt(jNumberField3.getText()); 
    minuten = Integer.parseInt(jNumberField2.getText());
    stunden = Integer.parseInt(jNumberField1.getText());
    zeit = sekunden + minuten*60 + stunden*60*60;//berechnet die zeit in sekunden
    TimeUnit.SECONDS.sleep(zeit);//here is the error
    System.out.println("zeit");
    }catch (InterruptedException e){
      //handle the exception
   }
}

答案 1 :(得分:1)

您需要处理拨打InterruptedException时可能发生的潜在sleep()。这就是您的代码出现编译错误的原因。

请查看有关JavaDocs的Catching and Handling Exceptions以了解有关异常处理的更多详细信息。

在您的情况下,您可以通过处理异常(例如:

)轻松解决此问题
public void jButton1_ActionPerformed(ActionEvent evt) {
    sekunden = Integer.parseInt(jNumberField3.getText()); 
    minuten = Integer.parseInt(jNumberField2.getText());
    stunden = Integer.parseInt(jNumberField1.getText());
    zeit = sekunden + minuten*60 + stunden*60*60;//berechnet die zeit in sekunden
    try {
        // tries to call sleep
        TimeUnit.SECONDS.sleep(zeit);//here is the error
    } catch (InterruptedException e) {
        // handles any possible exception during the call to "sleep()"
        e.printStackTrace(); // prints the exception stack trace to the console
    }
    System.out.println("zeit");
} // end of jButton1_ActionPerformed

异常处理中的一些好参考是: