1

I want to validate user input using the exception handling mechanism.

For example, let's say that I ask the user to enter integer input and they enter a character. In that case, I'd like to tell them that they entered the incorrect input, and in addition to that, I want them to prompt them to read in an integer again, and keep doing that until they enter an acceptable input.

I have seen some similar questions, but they do not take in the user's input again, they just print out that the input is incorrect.

Using do-while, I'd do something like this:

Scanner reader = new Scanner(System.in);  
System.out.println("Please enter an integer: ");
int i = 0;
do {
  i = reader.nextInt();
} while (  ((Object) i).getClass().getName() != Integer  ) {
  System.out.println("You did not enter an int. Please enter an integer: ");
}
System.out.println("Input of type int: " + i);

PROBLEMS:

  1. An InputMismatchException will be raised on the 5th line, before the statement checking the while condition is reached.

  2. I do want to learn to do input validation using the exception handling idioms.

So when the user enters a wrong input, how do I (1) tell them that their input is incorrect and (2) read in their input again (and keep doing that until they enter a correct input), using the try-catch mechanism?


EDIT: @Italhouarne

import java.util.InputMismatchException;
import java.util.Scanner;


public class WhyThisInfiniteLoop {

    public static void main (String [] args) {
        Scanner reader = new Scanner(System.in); 
        int i = 0; 
        System.out.println("Please enter an integer: ");

        while(true){
          try{
             i = reader.nextInt();
             break;  
          }catch(InputMismatchException ex){
             System.out.println("You did not enter an int. Please enter an integer:");
          }
        }

        System.out.println("Input of type int: " + i);
    }

}

3 Answers 3

3

In Java, it is best to use try/catch for only "exceptional" circumstances. I would use the Scanner class to detect if an int or some other invalid character is entered.

import java.util.Scanner;

public class Test {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        boolean gotInt = false;

        while (!gotInt) {
            System.out.print("Enter int: ");
            if (scan.hasNextInt()){
                gotInt = true;
            }
            else {
                scan.next(); //clear current input
                System.out.println("Not an integer");
            }
        }
        int theInt = scan.nextInt();
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

1

Here you go :

Scanner sc = new Scanner(System.in);
boolean validInput = false;
int value;
do{
    System.out.println("Please enter an integer");
    try{
        value = Integer.parseInt(sc.nextLine());
        validInput = true;
    }catch(IllegalArgumentException e){
        System.out.println("Invalid value");
    }
}while(!validInput);

Comments

1

You can try the following:

Scanner reader = new Scanner(System.in);  
System.out.println("Please enter an integer: ");
int i = 0;

while(true){
  try{
     i = reader.nextInt();
     break;  
  }catch(InputMismatchException ex){
     System.out.println("You did not enter an int. Please enter an integer:");
  }
}

System.out.println("Input of type int: " + i);

3 Comments

But while(true) is an infinite loop
@Solace No, because break will exit out of it whenever an exception is not thrown (meaning the input is an int).
I tested your code and it does enter an infinite loop, though not where I had (wrongly) expcted, but in the catch block. It keeps printing You did not enter an int. Please enter an integer:. See edit in question. Though why this is happening is beyond me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.