So, I have this program. The first method gets the input of an integer from the user and then passes it to another method which checks it to be in a range. That works fine. The problem is that if they enter something other than an int such as a double or a string, it causes an exception and the program crashes. Now, I need to handle this, as simple of just making it say what the issue was and then calling the method that requires them to enter the integer again, but I just can't remember how to handle this exception and unfortunately, my searches on google, here, and through my textbook have not been very helpful.
Right, so after looking into it, I get to a point where I can compile, except my exception handling isn't seeming to be working. It doesn't seem to be catching the exception and just returning it to JVM.
You are requesting the same input twice. Once before the try once inside it.
Never try handling an InputMismatchException (IME). The right way (in my opinion) to use a Scanner pointing to System.in is inside a utility class. You would have to write your own utility class. You can create a method something likeNow, a long time ago, Rob Spoor taught me that you can always avoid an IME when you use the keyboard by getting the program to ask for a new input and showed me something very similar to the above. A few more suggestions can be found in my old posts if you search them for Scanner nextInt hasNextInt and utility class.
If you create yourself a utility class, you can overload that method to return a value in a certain range only. Use something like while (i < min || i > max) …, and remember you will get a nice infinite loop if you pass max less than min
If you do that, you can be certain to avoid the IME for int inputs, but remember that technique does not work at all well if you are reading from a file. It would need locking if used in a multithreaded environment.