2014-03-31 49 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無關緊要,但對於其他許多例外情況。