我已经盯着它看了好几个小时了,想不出解决办法;我通常使用正则表达式处理这种类型的验证,但我正在尝试使用内置解决方案进行更改(显然,我不经常这样做):
private static double promptUserDecimal(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter a decimal");
try{
double input2 = Double.parseDouble(scan.nextLine());
return input2;
} catch(NumberFormatException e){
System.out.println("Sorry, you provided an invalid option, please try again.");
}
}
此错误是编译器未找到“return”,因此出现编译错误。如果我将“return”放在 try/catch 之外,我需要声明/初始化“input2”,这违背了操作的目的。感谢任何帮助...
最佳答案
如果你想让用户“请再试一次”,听起来你需要一个循环:
private static double promptUserDecimal(){
final Scanner scan = new Scanner(System.in);
// Ask for input until we get something valid
while (true) { // Terminated by return within
System.out.println("Enter a decimal");
try {
return Double.parseDouble(scan.nextLine());
} catch(NumberFormatException e){
System.out.println("Sorry, you provided an invalid option, please try again.");
// No return, so the loop will run again
}
}
}
关于Java try/catch - 找到 "return isn' t“或初始化 "variable isn' t”?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12773401/