在我的下面的代碼中,爲了當有人選擇退出電梯選項時添加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;
}
你預計會發生什麼?究竟發生了什麼? –
當選擇第三種情況時,在它說出口電梯後,我想讓它睡5秒,然後system.exit將終止程序 – user3151959
Try Thread.currentThread()。sleep(5000); – JHollanti