Reputation: 482
Scanner b = new Scanner(System.in);
public void menu() {
while (true) {
try {
System.out.println("Your options is:");
int option = 0;
option = b.nextInt();
b.nextLine();
if (option == 1)
add();
else if (option == 2)
delete();
else if (option == 3)
print();
else if (option == 4)
nr();
else if (option == 0)
break;
} catch (Exception e) {
System.out.println("Not a valid option!");
// break;
}
}
b.close();
}
Thing is that whenever I'm giving something else than the selected options(0,1,2,3,4) the function prints the message from the catch
and then asks for a new option but this thing is done repeatedly. If the break
is there, the whole execution is stopped and all I want is to ask again for an option but without the infinite loop. For example, if I type a "r" instead of a number, it should catch the exception and get again through the while
.
What am I missing?
Upvotes: 0
Views: 247
Reputation: 106440
The fundamental purpose of try...catch
is to try
to execute code that could throw an exception, and if it does throw the exception, catch
it and deal with it.
Invalid input in this case won't throw an exception, unless they managed to sneak a character in there, which would result in an infinite loop.
Instead of assuming that the user will enter in a digit - which is what Scanner#nextInt
generally assumes - read the whole line instead, and use Integer.parseInt()
to construct the int
.
option = Integer.parseInt(b.nextLine());
If this blows up because someone decided to put "foo" instead of "1", then you'll hit your exceptional case, and be able to re-enter values again.
Upvotes: 1
Reputation: 5637
do this
try
{
do
{
option=b.nextInt();
// continue
switch(option){
case 0:
break;
case 1: add();
break;
case 2: delete();
break;
case 3: print();
break;
case 4: nr();
break;
default: System.out.println("Not a valid option!");
break;
}
}while(!(option==1||option==2||option==3||option==4))
}
catch(Exception e){
System.out.println("Please enter a number");
}
Upvotes: 0