2014-10-10 89 views
-3

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

我得到布尔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; 


     } 

回答

0

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

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

您不能在return语句后执行任何代码。一旦执行return,该方法将结束。

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

由于您的行返回monthlyPayment;返回语句后,此范围内的额外代码将无法访问......因为返回语句必须是该方法的最后一个语句范围

0

该方法在您的第一个return语句上完成。

要么你可以把它放在一定的条件下。这样就有可能走得更远

0

return monthlyPayment;声明导致该问题。当你说return这意味着你告诉控制返回。没有更多的执行。

Unreachable并不意味着没有意义 - 它意味着某些代码块永远不会被执行,无论它是什么,那是编译器试图通过抛出错误告诉你的。

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

例如 -

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

return语句之后返回的方法中的线后,将无法到达编译器总是假定返回是任何类型的代码或方法

+1

块的执行结束点耶我接受@santhosh +1 :) – Raj 2014-10-10 05:19:44