public class Main {
public static void main(String[] args) {
final byte Month_in_yeah = 12;
final byte percent =100;
//avoid magic number in your code
Scanner scanner = new Scanner(System.in);
System.out.print("Principal: ");
int principal = scanner.nextInt();
System.out.print("Annual Interest Rate: ");
float annualInterest = scanner.nextFloat();
float monthInterest = annualInterest / percent / Month_in_yeah;
System.out.print("Period(Years): ");
byte years = scanner.nextByte();
int numberOfPayments = years * Month_in_yeah;
double mortgage = principal
* (monthInterest* Math.pow(1+monthInterest,numberOfPayments)
/(Math.pow(1+monthInterest,numberOfPayments)-1));
String mortgageFormatted = NumberFormat.getCurrencyInstance().format(mortgage);
System.out.println("Mortgage:" + mortgageFormatted);
}
}
过程描述:
1.declaing constance 声明常量(avoid magic number)
2.created scanner object 创建scanner对象
3.ask question and read it as an integer/float/byte 提问并将它储存为整数/小数/字节
4.after collect all datas then we calculate the mortgage 收集数据后计算贷款
5.use numberFormat class to format this value as currency,store and print it 储存打印
结果:
Principal: 200000 Annual Interest Rate: 0.32 Period(Years): 1 Mortgage:¥16,695.29



