MollyMoo
MollyMoo

Reputation: 75

Java User Input Error Handling

I have simple java program that accepts 3 user inputs of type integer, double and string. I would like to know the best/most efficient way to perform error handling on all of these inputs in order to keep the program running, inform the user they have entered an incorrect input and ask them the question again . Any help would be greatly appreciated.

Here is my code

    Scanner scan = new Scanner(System.in);
    int inputInt;
    double inputDbl;
    String inputString;


    System.out.print("Please enter a whole number: ");
    inputInt = scan.nextInt();      
    System.out.print("Please enter a decimal number: ");
    inputDbl = scan.nextDouble();
    System.out.print("Please enter a string: ");
    inputString = scan.next().toLowerCase();    

Upvotes: 1

Views: 8173

Answers (3)

MollyMoo
MollyMoo

Reputation: 75

Thanks for all the input people, you guys are awesome. I chose to just use a simple dowhile loop using a boolean trigger. I've tried using try catches before but ended up writing huge blocks of code to perform very basic input checks. So don't have any exception handling here, which I hope isn't gonna be necessary this way. Hopefully it doesn't break on me

do {
        System.out.print("Please enter a whole number: ");
        if (scan.hasNextInt()){     
        inputInt = scan.nextInt();
        validInput = true;
        } else
            System.out.println("You have entered incorrect input! Please enter a whole number only");
            scan.nextLine();
        } while (validInput == false);  

        validInput = false;

        do {
        System.out.print("Please enter a decimal number: ");
        ......
        ......

Upvotes: 3

Luke Melaia
Luke Melaia

Reputation: 1468

Splitting this into n methods where n is how many user inputs there are.

For each user input create a method that gets the input:

String getStringInput(){
    System.out.println("Enter input");
    String input = scan.next();

    //check the input to make sure it is correct
    if(input.equals("foo")){
        //if the input is incorrect tell the user and get the new input
        System.out.println("Invalid Input");
        //simply return this method if the input is incorrect.
        return getStringInput();
    }

    //return the input if it is correct
    return input;
}

For the main method that gets the input simply call the method:

void getAll(){
    String stringValue = getStringInput();
}

This now makes it easy to get any number of inputs and check if the are correct.

Upvotes: 2

px5x2
px5x2

Reputation: 1565

boolean validated = false;

// this keeps user locked until he/she provides valid inputs for all variables
while(!validated) {
  //get inputs here
  // ..

  // lastly
  validated = validateLogic(inInt, inDbl, inStr);
}

// keep going

If you want to validate separately for each input, you shuold write while loop 3 times.

Upvotes: 1

Related Questions