for the InputMismatchException from Scanner Class?
Scanner input = new Scanner(System.in);
int sc = input.nextInt();
System.out.println("\n\nInvalid option entered, please try again.");
Basically, I want to throw an error message if the user inputs anything other than an integer.
You got the throw/exception thing wrong. User is not supposed to interact with those. only crash your program when something either goes terribly wrong and you literally cant handle it or its something with runtime. Throwing an exception when a user gives you something other than int on a i assume main method which you're probably going to add a throws just crashes your program for no reason
try { Scanner input = new Scanner(System.in); int sc = input.nextInt(); } catch (InputMismatchException e){ System.out.println("\n\nInvalid option entered, please try again."); continue; } This is my syntax, is this wrong?
It isn't, but this isnt what you asked either. this is the right way you should catch the exception and ask the user again
Sorry, my bad. This is what I was looking for. I guess my wording of the issue was way off. Sorry about that. Thanks a lot for confirmation.
Обсуждают сегодня