我正在为一个贷款计算器工作。目标是根据客户信用评分改变利率。 if(finalScore< = 550)工作正常并将monthlyPayment打印到2个小数位,就像我想要的那样。我遇到的问题是当我转到下一个if语句“if(finalScore> 550&& finalScore< = 680)”时,它将错误地打印每月付款。输出看起来像147.04938.19就是一个例子。
我尝试将printf中的%.2f更改为%.2d并更正问题,但会引发非法格式异常。
这里有什么建议吗?
if(finalScore <= 550) {}
if (mortgage.equals(mlType)){}
if (lYears == 30) {
double interestRate = mIR550[0]/100 + pRate;
double monthlyRate = interestRate / 12.0;
int termInMonths = 360;
double monthlyPayments = ((mlAmount*monthlyRate)
/(1-Math.pow(1+monthlyRate, -termInMonths)));
System.out.printf("%.2f", monthlyPayments);
//prints fine here in format xxx.xx
正确输出的示例:
Please enter Credit Score:
550
Loan Type Mortgage:
Mortgage
Enter Years:
30
Enter Loan Amount:
20000
___________________________________
147.03
BUILD SUCCESSFUL (total time: 2 minutes 24 seconds)
输出错误的示例
Please enter Credit Score:
680
Loan Type Mortgage:
Mortgage
Enter Years:
30
Enter Loan Amount:
20000
___________________________________
147.03125.10
BUILD SUCCESSFUL (total time: 30 seconds)
发生问题的代码
if(finalScore >550 && finalScore <=680) {
if (mortgage.equals(mlType)){
if (lYears == 30) {
double interestRate = mIR680[0]/100 + pRate;
double monthlyRate = interestRate / 12.0;
int termInMonths = 360;
double monthlyPayments = ((mlAmount*monthlyRate)
/(1-Math.pow(1+monthlyRate, -termInMonths)));
System.out.printf("%.2f", monthlyPayments);
// output returns answer formatted xxx.xxxxx.xx not sure
why?
答案 0 :(得分:1)
你有两个if-then-else-if链;因此可能是System.out.printf的两倍。
原因是结束时:
if (finalScore <= 550) {
}
你可能想要包含第一个if-chain。
然后printf没有打印换行符,所以当打印说1.23和4.56时,打印1.234.56。换行符如下:
System.out.printf("%.2f%n", monthlyPayments);
你的IDE可能有一个格式化命令,这应该有帮助。