我们如何在java编程中添加时间延迟?

时间:2015-03-07 13:47:10

标签: java recursion time

我有这个程序:

import javax.swing.*;

public static void main()
{
    try {
        String stringyInp = JOptionPane.showInputDialog( null , "Enter your number" ) ; 
        int input = Integer.parseInt(stringyInp) ;
    }catch(Exception e) {
       JOptionPane.showMessageDialog(null ,"Enter only numerical values") ; //i want here to add a time delay of 3 seconds!How?
       main(); 
    }
    System.out.print( FACTORIAL(input)) ;


}// instance variables - replace the example below with your own



 public static int FACTORIAL(int number )
{
     if (number == 0){
         return 1 ;
        }
        else {

    return FACTORIAL(number-1) * number ;

}

那么我们如何才能添加时间延迟,如何执行延迟3秒的指令?我想在这个程序中添加3秒或2秒的延迟......

2 个答案:

答案 0 :(得分:0)

我认为您可以使用此代码。

   try {
     Thread.sleep(1000);
   } catch(InterruptedException ex) {
     Thread.currentThread().interrupt();
   }

答案 1 :(得分:0)

尝试正确编译的代码,工作并生成正确的阶乘:

你可以使用

Thread.sleep(3000);                 //3000 milliseconds is three seconds. 

持续3秒,和/或

Thread.sleep(2000);                 //2000 milliseconds is two seconds. 

两秒钟

你的代码有很多错误,但我试着编写一些有效且编译的东西,没有任何错误:

import javax.swing.*;


class factorial{
public static void main(String[] args)
{
    try {
        String stringyInp = JOptionPane.showInputDialog( null , "Enter your number" ) ; 
        int input = Integer.parseInt(stringyInp) ;
         Thread.sleep(3000);                 //3000 milliseconds is three seconds.
        int output = FACTORIAL(input);
        System.out.println(output);
    }catch(Exception e) {
       JOptionPane.showMessageDialog(null ,"Enter only numerical values") ; //i want here to add a time delay of 3 seconds!How?
    }


}// instance variables - replace the example below with your own



 public static int FACTORIAL(int number )
{
     if (number == 0){
         return 1 ;
        }
        else {

    return FACTORIAL(number-1) * number;

}
}
}

来自Java文档:

sleep
public static void sleep(long millis)
                  throws InterruptedException
Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers. The thread does not lose ownership of any monitors.
Parameters:
millis - the length of time to sleep in milliseconds
Throws:
IllegalArgumentException - if the value of millis is negative
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

在此处查看更多内容:http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#sleep(long)