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;
}