Java noob here so would really appreciate a little help. The program does exactly what it's supposed to do, except when the user enters the wrong variable type for the score.
It's a simple conversion program: user enters serial # of student, enters the score out of 100, and the program converts the score to a grade, i.e., 92 = a grade of A.
The issue is when the user enters a string rather than an integer; the following error message occurs:
Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Scanner.java:909)
I need a way to tell the user that if he/she doesn't enter an integer for the score, the program should print as much.
So, for example, you could construct a loop that parses the input and then sets a flag after successful parse, but in the case of a failure catches the exception, prints out a message to the user. The loop then repeats by virtue of the fact that you didn't set the "yes, we succeeded" flag.
Or, you could start with the flag being set to successful and then only explicitly set it to failure when you catch the exception. Six of one, half a dozen of the other.
Joined: Oct 13, 2005
Nice to see you again, Jeff
If you use Scanner (I know some people dislike Scanner; I don’t, but look here for a nasty potential pitfall), you can avoid both parsing and that Exception with the hasNextInt() method that Tony Docherty mentioned. What I won’t tell you is that I have written about that before, and you can find those posts by searching my posts for hasNextInt and Scanner. You can put that all in a utility class (which I recommend). I haven’t written about utility classes for ages, well over 13 minutes, and you can find some links here. You might even find a link to hasNextInt() in that post!
I have edited your post to take the bold print out; it is unnecessary. What is necessary, however, is the code button. When I edited your post I used that, and you can see how much better the code looks
Joined: Oct 13, 2005
By the way: you don’t need nested if-elses. You can do all the grade checking, including error messages for entries of 123 or -99, in one set of if-elses.