簡體   English   中英

如何讓thread.sleep工作

[英]How to get thread.sleep to work

在我下面的代碼中,我想添加一個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;
        }

sleep恢復后,你正在結束你的程序。

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

也許你正在尋找某種循環。 你沒有向我們展示switch后的內容,但也許那個停止java進程的System.exit(0)不應該存在。

擺脫System.exit(0)

如果您希望循環,請將您的方法包裝在循環中。 我的示例是一個無限循環,但如果您的應用程序接受用戶輸入,您可以很容易地擁有一個布爾標志作為循環條件。

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

此外,你應該在try-catch中包圍你的睡眠,而不是在你的main方法上聲明一個拋出...這是一個很好的做法,捕獲你可以處理的異常,並拋出你無法處理的異常,可以使用早期的堆棧幀。 通常,您不希望main()方法具有throws子句,因為它可能導致應用程序提前終止。 對於特定情況下的InterruptedException ,這並不重要,但是對於許多其他異常也是如此。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM