在我下面的代码中,我正在尝试添加一个 thread.sleep ,以便当有人选择退出电梯的选项时,我不确定我输入的使其 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
之后的内容,但也许是System.exit(0)
,它会停止 java 进程,不应该在那里。
关于java - 如何让 thread.sleep 工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22771005/