Sunday 2 December 2012

Java Input Checking

If you've been programming with Java you're surely aware of the problems of taking user input, maybe you're asking for an integer and the user enters a string and the program crashes. You could write lines of code every time to stop your programs crashing and get the input you want but that needlessly bulk up on your code.

With some inspiration from Java 6 Illuminated, I wrote a class for handling user input with the Scanner class. This way you can ensure your program doesn't crash and at the same time get the correct results.

So to the code:
The method takes in a String, being the message they want to print to the console and then the loop will run until the user enters a valid integer.

Example use:
Sometimes the programmer might want to have a set range of valid values. The InputChecker class includes overloaded methods for specifying range:
Let's take an example where we ask for a persons age. We know that this will always be a positive number and is unlikely to be above 150 so we set the range from 0-150:
The example code above will loop until the user enters a number between 0-150 and then return that number.

So there you have it a class for checking input. The class works with shorts, ints, longs, floats, doubles, bytes and booleans. All you need to do is where the examples used readInt, replace Int with the data type you are using.

Download the InputChecker class below and move the file to the folder you keep your classes in:

Download

1 comment:

  1. hello; please give sample code for validating user input with the following conditions:
    a. input must be integer
    b. input must be between 1 - 100
    c. input must not be the same as prior entries

    Thanks

    ReplyDelete