java - 尝试验证传递给方法的值
问题描述
我有一个程序试图验证传递的值。我希望用户输入任何内容,并且我将其传递给的方法将验证输入是否有效。
这是我的代码:
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 循环可以解决问题,但它没有做任何事情。
解决方案
你不需要循环,你需要递归
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);
}
}
推荐阅读
- javascript - 如何使用javascript从下拉列表中删除任何多个选择的项目
- r - Creating new column that flags row based on conditions
- scala - 在 scala 库中查找隐式
- apache-kafka - Purpose of +tmp in Kafka hdfs connect
- java - Android camera preview freeze when switching the camera?
- autodesk-forge - Autodesk Forge 文档批准状态
- c++ - 参考 Abaqus C++ API 静态库读取 ODB 文件
- ruby-on-rails-5 - 在 Rails 5 更新后,带有acts_as_tenant 的模型验证失败
- github - Git Hub 页面未部署。(404)
- ios - 我无需请求许可即可访问 iOS 照片库