0

In my Java code shown below, I'm accepting user input of two doubles, and wrapping those values in a try-catch that handles an InputMismatchException. I've also wrapped a do-while loop around this try-catch block. I'm trying to craft the code in a way that handles the case where if a user inputs the wrong type for "number2", then the loop doesn't start over and ask the user to input "number1" all over again. I've been scratching my head on the best way to implement this and am open to any feedback or suggestions.

So the test case would be; the user inputs the right type for number1, but the wrong type for number2, in which case, how can I implement the code so that it only asks for re-entry of number2 instead of re-starting the entire loop. I've tried nested try-catch, nested do-whiles, etc. Any thoughts?

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

class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    boolean continueInput = true;

    do {
      try {
      System.out.print("Enter your first number: ");
      double number1 = input.nextDouble();

      System.out.print("Enter your second number: ");
      double number2 = input.nextDouble();

      System.out.println("You've entered the numbers " + number1 + " " + number2);

      continueInput = false;
    }
      catch (InputMismatchException ex) {
        System.out.println("Try again, a double is required.");
        input.nextLine();
      }
    } while (continueInput);
  }
}
3
  • 1
    You can have separate try-catch blocks Commented Jun 18, 2020 at 14:17
  • You could define your variables number1 and number2 as Objects and before the loop and initialize them with null: Double number1 = null, then you just wrap the two lines of code that are asking for input of number1 in a simple if (number1==null) Commented Jun 18, 2020 at 14:20
  • Okay, just so that I understand your response, you mean that I can setup each user input within it’s own try catch block? Commented Jun 18, 2020 at 14:20

3 Answers 3

2

try this,

        Scanner input = new Scanner(System.in);

        boolean continueInput = true;
        double number1 = 0;
        while (continueInput) {
            try {
                System.out.print("Enter your first number: ");
                number1 = input.nextDouble();
                continueInput = false;
            } catch (InputMismatchException ex) {
                System.out.println("Try again, a double is required.");
                input.nextLine();
            }
        }

        continueInput = true;
        double number2 = 0;
        while (continueInput) {
            try {
                System.out.print("Enter your second number: ");
                number2 = input.nextDouble();
                continueInput = false;
            } catch (InputMismatchException ex) {
                System.out.println("Try again, a double is required.");
                input.nextLine();
            }
        }
        System.out.println("You've entered the numbers " + number1 + " " + number2);
Sign up to request clarification or add additional context in comments.

1 Comment

Your solution is very similar to CodingTil's answer except you use a while loop instead of a do-while loop.
1

You can extract method which takes Supplier

private <T> T executeWithRetry(String initialText, String retryText, Supplier<T> supplier) {
    System.out.println(initialText);
    while (true) {
        try {
            return supplier.get();
        } catch (InputMismatchException ex) {
            System.out.println(retryText);
      }
    };
}

And use it like

double number1 = executeWithRetry(
    "Enter your first number: ",
    "Try again, a double is required.",
    () -> input.nextDouble()
)

Comments

1

Just split the process of reading the 2 values apart. This way you can individually check if an InputMismatchException occurs and handle it individually for each variable.

continueInput = false;
do {
    try {
        System.out.print("Enter your first number: ");
        double number1 = input.nextDouble();
    } catch (InputMismatchException ex) {
        System.out.println("Try again, a double is required.");
        continueInput = true;
    }
} while (continueInput);

continueInput = false;
do {
    try {
        System.out.print("Enter your second number: ");
        double number2 = input.nextDouble();
    } catch (InputMismatchException ex) {
        System.out.println("Try again, a double is required.");
        continueInput = true;
    }
} while (continueInput);

1 Comment

this would be better as an answer if you added an explication

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.