【问题标题】:Unreachable Statement with this boolean带有此布尔值的无法访问的语句
【发布时间】:2014-10-10 05:01:23
【问题描述】:

我在这个布尔声明中遇到了无法访问的语句错误。 我知道无法访问通常意味着毫无意义,但我需要 isValid 语句才能让我的 while 循环正常工作。为什么我会收到此错误,我该如何解决?这是我的代码。

我在 boolean isValid 上遇到错误;

提前感谢您的任何意见。

public static double calculateMonthlyPayment(double loanAmount, double monthlyInterestRate, int months)
        {
            double monthlyPayment =
            loanAmount * monthlyInterestRate/
            (1 - 1/Math.pow(1 + monthlyInterestRate, months));
            return monthlyPayment;
            boolean isValid;
                      isValid = false;

            //while loop to continue when input is invalid
            while (isValid ==false)
            {
                System.out.print("Continue? y/n: ");
                                String entry;
                entry = sc.next();
                if (!entry.equalsIgnoreCase("y") && !entry.equalsIgnoreCase("n"))
                {
                    System.out.println("Error! Entry must be 'y' or 'n'. Try again.\n");
                }
                else
                {
                    isValid = true;
                } // end if

                sc.nextLine();

            } // end while
                        double entry = 0;
        return entry;


        }

【问题讨论】:

    标签: java java.util.scanner unreachable-code


    【解决方案1】:

    是的,您在上一行有一个return。方法完成。

    return monthlyPayment; // <-- the method is finished.
    boolean isValid; // <-- no, you can't do this (the method finished on the
                     //     previous line).
    

    【讨论】:

      【解决方案2】:

      return 语句之后不能执行任何代码。一旦return被执行,该方法就会结束。

      return monthlyPayment;
      //this and the rest of the code below will never be executed
      boolean isValid;
      

      【讨论】:

        【解决方案3】:

        由于您的线路返回每月付款;在返回语句之后,此范围内的额外代码将无法访问......因为返回语句必须是该方法范围的最后一条语句

        【讨论】:

          【解决方案4】:

          方法在您的第一个 return 语句结束。

          您可以将其置于某种条件下。这样才有可能走得更远

          【讨论】:

            【解决方案5】:

            return monthlyPayment; 语句导致问题。当您说return 时,这意味着您正在告诉控件返回。不再执行。

            Unreachable 并不意味着毫无意义——它意味着某些代码无论如何都不会被执行,这就是编译器试图通过抛出错误来告诉你的。

            因此,如果您不需要 unreachable 代码块,您可以删除它,或者适当或有条件地将您的方法修改为 return

            例如-

            //even if you use the below statement in your code
            //compiler will throw unreachable code exception
            return monthlyPayment;;
            

            【讨论】:

              【解决方案6】:

              返回方法后,return 语句后面的行将无法到达编译器始终假定 return 是任何类型的代码块或方法的执行终点

              【讨论】:

                猜你喜欢
                • 2018-06-23
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2014-02-02
                • 1970-01-01
                • 2013-10-21
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多