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

本文介绍了如何使用Java编写一个简单的房贷计算器。首先声明常量,使用Scanner对象获取用户输入,收集数据后计算贷款。通过NumberFormat格式化输出货币值。接着增加了数字限制功能,用while循环确保输入有效。为了代码复用,定义了readNumber()和calculateMortgage()方法。最后,新增了计算每月还款和支付计划的功能,包括calculateBalance()方法,以显示剩余余额。
最低0.47元/天 解锁文章
888

被折叠的 条评论
为什么被折叠?



