The problem in your current code is that you’re always trying to read an int
so when receiving a non-integer input you can’t handle the error in the right way. Modify this to always read a String
and convert it into an int
:
int numberOfPeople = 0;
while (numberOfPeople <= 0) {
try {
System.out.print("Enter the number of people: ");
numberOfPeople = Integer.parseInt(input.nextLine());
} catch (Exception e) {
System.out.print("Wrong input!");
numberOfPeople = 0;
}
}
//continue with your life...
solved Try-Catch inside a loop