Some Number Format Exceptions
Some Number Format Exceptions. Now we need to quickly survey a couple programs that trap for NumberFormatExceptions. These are particularly important for dealing with non-numeric or blank inputs from a user. Remember that we stated in the last webpage that when a Java program encounters something that doesn't quite fit the required format or structure the program is said to throw an exception. You should also remember that
Our first program returns to one of our earlier programs where we got the user to input two integers and then returned their product while echoing the inputs. Remember how it crashed when we gave it anything other than the correct types of inputs. We will reorganize it and put in some try and catch blocks to reduce the crashes and give feedback to the user about how they need to change their inputs. The following program is again an application, it should be quite easy to convert it to an applet. You should call the file IntegerFormatExceptionPrimitive.java. I put primitive in the name because we will improve on the code in future web pages as we learn more Java. |
import javax.swing.JOptionPane; public class IntegerFormatExceptionPrimitive {
} // end class IntegerFormatExceptionPrimitive |
Now you should compile the program and execute it.
Hopefully, you have learned the steps to do this by now. At a general level, I have reorganized the code so that it
Notice how the parse statements are within the try blocks. Notice how the catch blocks are looking for NumberFormatExceptions. Now you should run the program trying a number of different inputs such as
The results should surprise you. It would be nice to be able to do more, like get both inputs from the user before giving them an error message. But that requires some more Java code. Floating Point Exceptions. Now we will modify this same program slightly to deal with floating point numbers. You should call this file FloatFormatExceptionPrimitive.java. This is directly analogous to the previous program except that we are looking for floating point numbers. In reality, parsing floats has considerably more capacity for handling a variety of user inputs. Thus, in order to get the program to throw an error your going to need to enter text or a blank. |
import javax.swing.JOptionPane; public class FloatFormatExceptionPrimitive {
} // end class FloatFormatExceptionPrimitive |
Much more will be said about the code in class, but
there are just a few differences between this and the previous program
having to do with dealing with floating point numbers. It should be fairly obvious that you could easily convert this to trap for doubles. Nor would it take much to convert these into applets. |