Java Lab #3: Input Validation

  1. Create a new project in your Eclipse workspace named Lab03 with a class of the same name. Put a main method in that class. I suggest you start by copying your code from Lab #2 into Lab #3's main method.

  2. In this lab you will enhance your program from last week to do more comprehensive validation of its input. Checking input for "sanity" is a common concern and many programs are not as careful about it as they should be.

    Consider the following examples of invalid fractions (invalid according to last week's program):

    To deal with these problems proceed as follows:

    1. Use the nextLine() method in the Scanner class to read an entire line of text for each fraction. Use the indexOf() method in the String class to search for the '/' character in that line. It is an error if no '/' character exists.

    2. Use the substring() method in class String to split the input into two parts: the part before the slash (the numerator text), and the part after the slash (the denominator text). Use the trim() method to remove all leading and trailing whitespace from each part.

    3. Convert the numerator and denominator strings into integers. If s is a String you can convert it to an integer with Integer.parseInt(s).

    4. It is an error if the denominator is zero.

    5. If the denominator is negative, multiply both numerator and denominator by -1 to move the negative sign to the numerator.

    6. Both fractions need to be processed in this way with suitable error messages produced if problems are found. You will probably find this extremely annoying to do if you use if ... else statements (try it and see). HINT: For this program you can call System.exit(1) whenever an error is detected to immediately terminate the program at that point.

  3. Test your program by providing various forms of erroneous input to verify that all error conditions are properly checked and handled.

  4. OPTIONAL: If you are looking for a challenge, see if you can also detect and deal with erroneous input such as 1 / / 2. Handling this error is not a required part of this lab.

Turn in your final program with appropriate comments. Be sure your name is on your submission.