简体   繁体   English

Java try-catch 在 do-while 循环内

[英]Java try-catch inside of a do-while loop

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.在下面显示的 Java 代码中,我接受两个双精度的用户输入,并将这些值包装在处理 InputMismatchException 的 try-catch 中。 I've also wrapped a do-while loop around this try-catch block.我还在这个 try-catch 块周围包裹了一个 do-while 循环。 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.我正在尝试以处理以下情况的方式编写代码:如果用户为“number2”输入错误类型,则循环不会重新开始并要求用户重新输入“number1”。 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.用户为 number1 输入了正确的类型,但为 number2 输入了错误的类型,在这种情况下,我该如何实现代码以便它只要求重新输入 number2 而不是重新启动整个循环。 I've tried nested try-catch, nested do-whiles, etc. Any thoughts?我试过嵌套 try-catch、嵌套 do-whiles 等。有什么想法吗?

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);
  }
}

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()
)

Just split the process of reading the 2 values apart.只需将读取 2 个值的过程分开即可。 This way you can individually check if an InputMismatchException occurs and handle it individually for each variable.这样,您可以单独检查是否发生 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);

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM