开发者社区> 问答> 正文

是否可以创建带有双重输入的异常处理方法,该方法可以在Java中初始化变量?

我想知道是否可以创建这样的异常处理方法:


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

        do {
            try {
                double a = in.nextDouble();
                double b = in.nextDouble();
                double c = in.nextDouble();

                // some code that works with a, b and c variables
            }
            catch(java.util.InputMismatchException exc) {
                System.out.println("Wrong input.");
                in.next();
            }
        } while(true);
    }
    ```
因此,我可以从键盘输入一些变量,如果不是两倍,则显示“输入错误”。并希望您再次输入。是否有可能创建处理所有这些问题的方法?在Java中甚至可以创建可以像这样工作的方法:

double a, b, c; myMethodTest(a);


并实际上将以与第一个代码相同的方式工作?如果可能的话,该怎么做?我知道有一个错误提示“变量可能尚未初始化”,但是有没有解决的方法?方法是否可以初始化我放入的变量(),例如myMethodTest(a)可以初始化a并为我执行所有异常处理?

问题来源:Stack Overflow

展开
收起
montos 2020-03-22 22:37:09 851 0
1 条回答
写回答
取消 提交回答
  • 如下进行:

    import java.util.Scanner;
    
    public class Main {
        public static void main(String[] argv) {
            Scanner in = new Scanner(System.in);
            double a, b, c;
            a = getDouble(in, "Enter the value of a: ");
            b = getDouble(in, "Enter the value of b: ");
            c = getDouble(in, "Enter the value of c: ");
            System.out.println(a + ", " + b + ", " + c);
        }
    
        static double getDouble(Scanner in, String inputMessage) {
            double n = 0;
            boolean valid = true;
            do {
                valid = true;
                System.out.print(inputMessage);
                try {
                    n = Double.parseDouble(in.nextLine());
                } catch (NullPointerException | NumberFormatException e) {
                    System.out.println("Invalid input. Try again");
                    valid = false;
                }
            } while (!valid);
            return n;
        }
    }
    

    运行示例:

    Enter the value of a: a
    Invalid input. Try again
    Enter the value of a: abc
    Invalid input. Try again
    Enter the value of a: 10
    Enter the value of b: 10.5
    Enter the value of c: hello
    Invalid input. Try again
    Enter the value of c: 20
    10.0, 10.5, 20.0
    

    回答来源:Stack Overflow

    2020-03-22 22:37:57
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
Spring Cloud Alibaba - 重新定义 Java Cloud-Native 立即下载
The Reactive Cloud Native Arch 立即下载
JAVA开发手册1.5.0 立即下载