2014-10-10 100 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