Java try-catch внутри цикла do-while - PullRequest
0 голосов
/ 18 июня 2020

В моем коде Java, показанном ниже, я принимаю ввод данных пользователем двух двойников и заключаю эти значения в try-catch, который обрабатывает InputMismatchException. Я также обернул do-while l oop вокруг этого блока try-catch. Я пытаюсь создать код таким образом, чтобы он обрабатывал случай, когда если пользователь вводит неправильный тип для «number2», то l oop не запускается заново и просит пользователя ввести «number1» на всем протяжении очередной раз. Я долго ломал голову над тем, как это лучше всего реализовать, и открыт для любых отзывов и предложений.

Итак, тестовый пример: пользователь вводит правильный тип для number1, но неправильный тип для number2, и в этом случае, как я могу реализовать код, чтобы он запрашивал только повторный ввод number2 вместо перезапуска всего l oop. Я пробовал вложенные try-catch, вложенные do-while и т. Д. c. Есть предположения?

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 голос
/ 18 июня 2020

Просто разделите процесс чтения двух значений. Таким образом, вы можете индивидуально проверить, возникает ли исключение InputMismatchException, и обрабатывать его индивидуально для каждой переменной.

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 голос
/ 18 июня 2020

попробуйте это,

        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);
1 голос
/ 18 июня 2020

Вы можете извлечь метод, который принимает 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);
      }
    };
}

, и использовать его как

double number1 = executeWithRetry(
    "Enter your first number: ",
    "Try again, a double is required.",
    () -> input.nextDouble()
)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...