Clean Coding (Refactoring Repetitive Patterns):

Whenever I use decimals for my inputs i.e the Annual Interest Rate,
I get “Exception in thread” Error:
Before refactoring I did not have this issue;
Does anyone know why this is happening?

int principle= (int) readNumber("Principle :", 1_000 , 1_000_000 );
       float annualInterest= (float) readNumber("Annual Interest Rate :", 1 , 30 );
       byte years= (byte) readNumber("Period (Years) : ", 1 , 30 );

        double mortgage = calculateMortgage(principle, annualInterest, years);

        String mortgageFormatted = NumberFormat.getCurrencyInstance().format(mortgage);
        System.out.println("Mortgage: " + mortgageFormatted);
    }

    public static double readNumber (String prompt, double min, double max) {
        Scanner scanner = new Scanner(System.in);
        double value;
        while (true) {
            System.out.print(prompt);
            value = scanner.nextInt();
            if (value >= min && value <=max)
                break ;
            System.out.println("Please Enter a value between " + min + "and " + max );
        }
        return value;
    }

    public static double calculateMortgage(
            int principle,
            float annualInterest,
            byte years) {

        final byte MONTHS_IN_YEAR = 12;
        final byte Percent = 100;

        float monthlyInterest = annualInterest / Percent / MONTHS_IN_YEAR;
        short numberOfPayments = (short)(MONTHS_IN_YEAR * years);
        double  mortgage = principle * (monthlyInterest * Math.pow( 1 + monthlyInterest, numberOfPayments )
                / (Math.pow( 1 + monthlyInterest, numberOfPayments) -1
        ));
        return mortgage;
    }

You are asking the Scanner for the nextInt which expects an integer as an input.

1 Like

Not a Scanner - But for me seems - in line, where you initialize mortgageFormated as a string but trying to format number. in that case, you should convert to string Or my suggestion ```
mortgageFormatted

suddenly lost part of my comment :slight_smile: use double for variable mortgageFormatted