首页 > 解决方案 > 尝试验证传递给方法的值

问题描述

我有一个程序试图验证传递的值。我希望用户输入任何内容,并且我将其传递给的方法将验证输入是否有效。

这是我的代码:

public static void main(String[]args) {
    Scanner input = new Scanner(System.in);
    ChequingAccount a = new ChequingAccount();
    double deposit = inputCheck("Enter deposit amount: ", input);
    a.setDeposit(deposit);
}

public static double inputCheck(String prompt, Scanner input) {
    boolean userValid = false;
    do {
        System.out.print(prompt);
        double user;
        try {
            user = input.nextDouble();
            if (user < 0) {
                throw new IllegalArgumentException("Value cannot be lower than 0");
            }
            userValid = true;
       } catch (InputMismatchException e) {
            System.out.println("The value entered is not a number");
            user = inputCheck(prompt, input);
            input.nextLine();
       } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
            user = inputCheck(prompt, input);
       }
         return user;
    } while (!userValid);
}

代码可以工作,除了当方法捕获 时InputMismatchException,代码将循环很多次并中断程序。我认为添加一个 doWhile 循环可以解决问题,但它没有做任何事情。

标签: java

解决方案


你不需要循环,你需要递归

public static double inputCheck(String prompt, Scanner input) {
        double user;
        try {
            user = input.nextDouble();
            if (user < 0) {
                throw new IllegalArgumentException("Value cannot be lower than 0");
            }
            return user;
        } catch (InputMismatchException e) {
            System.out.println("The value entered is not a number");
            return inputCheck(prompt, input);
        } catch (IllegalArgumentException ex) {
            System.out.println(ex.getMessage());
            return inputCheck(prompt, input);
        }
    }

推荐阅读