Search code examples
javajava.util.scannerunreachable-code

Unreachable Statement with this boolean


I'm getting an unreachable statement error with this boolean declaration. I know unreachable usually means meaningless, but I need the isValid statement for my while loop to work. Why am I getting this error and how can I fix it? Here is my code.

I'm getting the error on boolean isValid;

Thank you in advance, for any input you might have.

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;


        }

Solution

  • Yes, you have a return on the previous line. The method is done.

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