Java try/catch - 找到 "return isn' t“或初始化 "variable isn' t”?

标签 java compiler-errors

我已经盯着它看了好几个小时了,想不出解决办法;我通常使用正则表达式处理这种类型的验证,但我正在尝试使用内置解决方案进行更改(显然,我不经常这样做):

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/

相关文章:

eclipse - Eclipse编译器错误和QuickFix建议之间的映射

excel - 编译错误: Syntax Error caused by code inserting a excel formula

java - 使用RegEx在html源中查找特定字符串

java - 如何使用java在HTML文档中定位特定的td

java - Python 请求 : POST JSON and file (multiform data) in 1 single request

compiler-errors - gccgo 不知道 -fgo-relative-import-path

haskell - 没有最后一个参数的函数组成

java - 离线时的android mqtt数据持久化

java - 使用 java 在 xml 元素中包含重复的命名空间

sql - 编译错误 “Method of Data Member Not Found”-DoCmd.Query表单 Access SQL