Hey there!
I was doing the java course with Mosh and I had to do the Mortgage Calculator. I’ll copy the code in this Topic as I had some trouble with it…
As far as I know, when you use “float variable = nextFloat()” you can input a decimal in the terminal, such as 1.1. As you can see in that code, I do that but for some reason I can’t input decimal numbers on that section.
I hope you guys can help me.
Also, if there’s a cleaner way to share code definitely let me know!
package me.oriol;
import java.text.NumberFormat;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
final byte MONTHS_IN_YEAR = 12;
final byte PERCENT = 100;
int principal;
double monthlyInterest;
int numberOfPayments;
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.print("Principal ($1k - $1M): ");
principal = scanner.nextInt();
if ( principal >= 1000 && principal <= 1_000_000 )
break;
System.out.println("Enter a number between 1,000 and 1,000,000.");
}
while (true) {
System.out.print("Annual interest Rate: ");
double annualInterest = scanner.nextFloat();
if ( annualInterest > 0 && annualInterest <= 30 ) {
monthlyInterest = annualInterest / MONTHS_IN_YEAR / PERCENT;
break; }
System.out.println("Enter a value between 1 and 30.");
}
while (true) {
System.out.print("Period (Years): ");
byte years = scanner.nextByte();
if ( years > 0 && years <= 30 ) {
numberOfPayments = years * MONTHS_IN_YEAR;
break; }
System.out.println("Enter a value between 1 and 30");
}
double mortgage = principal
* ( monthlyInterest * Math.pow( 1 + monthlyInterest, numberOfPayments )
/ ( Math.pow( 1 + monthlyInterest, numberOfPayments) - 1 ));
String mortgageCurrency = NumberFormat.getCurrencyInstance().format(mortgage);
System.out.println("Mortgage: " + mortgageCurrency);
}
}