Reputation: 91
In my code below im am tring to add a thread.sleep for when someone chooses the option to exit the lift, i am not sure whats wrong with the code i entered to make it sleep.I already included the Interrupted exception so can someone tell me where i went wrong.
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;
}
Upvotes: 0
Views: 130
Reputation: 2012
Get rid of the System.exit(0)
Wrap your method in a loop if you want it to loop. My example is an infinite loop, but if your application accepts user input you can just as easily have a boolean flag that serves as the loop condition.
public static void main(String... args) throws InterruptedException {
while(true){
//all of your code
}
}
Also you should surround your sleep in a try-catch instead of declaring a throws on your main method... it is good practice to catch exceptions you can handle, and throw exceptions that you cannot handle to earlier stack frames that can. Typically you don't want your main() method to have a throws clause as it can cause the premature termination of your application. This doesn't really matter for InterruptedException
in your specific case, but does for many other exceptions.
Upvotes: 1
Reputation: 279960
You're ending your program after the sleep
returns.
Thread.sleep(5000);
System.exit(0);
Maybe you're looking for a loop of some kind. You haven't shown us what comes after the switch
, but maybe that System.exit(0)
, which stops the java process, shouldn't be there.
Upvotes: 1