Java try/catch - "找不到返回"或"未初始化变量"?

fel*_*s77 5 java compiler-errors

我已经盯着这几个小时了,无法想到解决方案; 我通常用regex处理这种类型的验证,但我试图使用内置的解决方案进行更改(显然,我不经常这样做):

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.");
    }
}
Run Code Online (Sandbox Code Playgroud)

这个错误是编译器找不到"返回",所以我得到一个编译错误.如果我将"return"放在try/catch之外,我需要声明/初始化"input2",这会破坏操作的目的.任何帮助表示赞赏......

ILM*_*tan 0

您需要从(或在捕获后)返回或抛出一些东西。从您向用户输出的结果来看,您似乎只想再次做同样的事情。只需再次调用该方法并返回结果即可。

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 promptUserDecimal();
    }
}
Run Code Online (Sandbox Code Playgroud)