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
二.增加功能:数字限制
package com.company;
import org.w3c.dom.ls.LSOutput;
import java.awt.*;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Locale;
import java.util.Scanner;
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
int principal = 0;
float monthInterest = 0;
int numberOfPayments = 0;
Scanner scanner = new Scanner(System.in);
while(true){
System.out.print("Principal: ");
principal = scanner.nextInt();
if (principal >= 1000 &a