# Java Mortgage Calculator

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

}

To clarify, what error or output are you getting and what did you expect? Ideally including whatever input you are providing.

Hii dude,

Replace the double datatype to float in monthlyInterst

int principal;
float monthlyInterest;
int numberOfPayments;

Then you will able to apply decimal numbers

You also need to that in monthly interest while loop

Well, this was more of a sharing issue actually, coz i sent the wrong code. In my code I had it like you told me. Luckily, though, I figured the issue out… I needed to input “1,1” instead of “1.1” because I was doing it with € instead of \$. So ye, that was a typing issue, thanks!

2 Likes