2014-03-31 51 views
0

在我的下面的代码中,为了当有人选择退出电梯选项时添加thread.sleep,我不确定我为了让它进入睡眠状态而输入的代码有什么问题。我已经包含了中断异常,所以有人可以告诉我我错了什么地方。如何让thread.sleep工作

import java.util.Arrays; 
import java.util.Scanner; 

public class username{ 

    public static void main(String... args) throws InterruptedException { 

     String[] verifiedNames = { "barry", "matty", "olly", "joey" }; 
     System.out.println("choose an option"); 
     System.out.println("Uselift(1)"); 
     System.out.println("see audit report(2)"); 
     System.out.println("Exit Lift(3)"); 

     Scanner scanner = new Scanner(System.in); 
     int choice = scanner.nextInt(); 

     switch (choice) { 
      case 1: 
      scanner.nextLine(); // get '\n' symbol from previous input 
      int nameAttemptsLeft = 3; 
      while (nameAttemptsLeft-- > 0) { 
       System.out.println(" Enter your name "); 
       String name = scanner.nextLine(); 

       if (Arrays.asList(verifiedNames).contains(name)) { 
        System.out.println("dear " + name + " you are verified " + 
        "you may use the lift, calling lift "); 
        break; // break out of loop 
       } 
      } 
      if (nameAttemptsLeft < 0) { 
       System.out.println("Username Invalid"); 
      } 
      break; 

      case 2: 
      System.out.println("option 2"); 
      break; 
      case 3: 
      System.out.println(" Please Exit Lift "); 
      Thread.sleep(5000); 
      System.exit(0); 
      break; 
     } 
+3

你预计会发生什么?究竟发生了什么? –

+0

当选择第三种情况时,在它说出口电梯后,我想让它睡5秒,然后system.exit将终止程序 – user3151959

+0

Try Thread.currentThread()。sleep(5000); – JHollanti

回答

1

sleep返回后,您即将结束您的程序。

Thread.sleep(5000); 
System.exit(0); 

也许你正在寻找某种循环。你没有向我们展示switch之后发生的事情,但是可能那个阻止java进程的System.exit(0)不应该在那里。

+0

我真的很想循环回到程序的开始,所以我可能应该将其更改为system.close ?,但我不知道该怎么做,但我仍然需要延迟来表示它的时间把门关上,所以一个人可以安全地离开电梯等。@Sotirios Delimanolis – user3151959

1

摆脱System.exit(0)

裹在一个循环的方法,如果你想让它循环。我的例子是一个无限循环,但如果你的应用程序接受用户输入,你可以很容易地有一个布尔标志作为循环条件。

public static void main(String... args) throws InterruptedException { 
    while(true){ 
    //all of your code 
    } 
} 

你也应该包围一个try-catch你的睡眠代替声明抛出你的主要方法......这是很好的做法,抓住你可以处理异常,并抛出,你不能处理早期异常堆栈帧可以。通常,您不希望main()方法具有throws子句,因为它可能会导致应用程序提前终止。这在你的特定情况下对InterruptedException无关紧要,但对于其他许多例外情况。