AP Computer Science Java: Lesson 3.6
Repetitive Statements - Error-Checking with while


Lesson 3.6 - Error-Checking with while

Purpose: To learn how to write better error-checking using a while loop

Error! 
In Unit 2 we discussed some basic error-checking of user input. For example, if we want the user to enter an even integer, we could have used the following code:

   System.out.print("Enter an even integer: ");
   number = keybd.readInt();
   if(number%2==1)
   {
      System.out.println("Bad input.");
   }
   else
   {
      System.out.println("Thank you!");
   }

That works fine at identifying an error. But for error-checking to be truly useful, we need to allow the user to re-enter their input until they get it right. This requires repetition in general and specifically, a while loop. Let's modify the above code to see an example.

   System.out.print("Enter an even integer: ");
   number = keybd.readInt();
   while(number%2==1)
   {
      System.out.println("Bad input. Try again!");
      System.out.print("Enter an even integer: ");
      number = keybd.readInt();

   }
   System.out.println("Thank you!");

In this version, the if statement is replaced by a while loop. The loop will not exit until the condition is false, meaning until the number entered is even. If the user enters an odd integer, the loop will tell them they made a mistake and require them to perform the input again. This will continue until they get it correct.

Another example   Suppose we need the user to enter an integer between 1 and 5. We can use the following to ensure correct input:

   System.out.print("Enter an integer from 1-5: ");
   number = keybd.readInt();
   while(number<1 || number>5)
   {
      System.out.println("Bad input. Try again!");
      System.out.print("Enter an integer from 1-5:");
      number = keybd.readInt();

   }
   System.out.println("Thank you!");

In closing, The while loop version of error-checking is much more useful than the if statement version as it gives the user the ability to re-enter their input until they get it right. This helps maintain the integrity of the data entered by users and ensures that the program will not continue until it receives the correct information. From now on, when writing error-checking code, use a while loop.

© DanShuster.com