The while loop is continues running when using try catch function, the while loop just skipping try{} and run the catch{} when looping every time.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean x = true;
while(x){
try{
System.out.print("Who are you? 1. Student, 2. Librarian (Please type in numbers) : ");
int user = scanner.nextInt();
if (user == 1){
student();
}else if (user == 2){
librarian();
}else{
System.out.println("Please only enter 1 or 2");
}
}catch (InputMismatchException e){
System.out.println("Wrong input, please only enter numbers");
continue;
}
}
This is the output
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Who are you? 1. Student, 2. Librarian (Please type in numbers) : Wrong input, please only enter numbers
Aucun commentaire:
Enregistrer un commentaire