我正在尝试编写一个程序,允许用户创建“贷款”对象,并在将其放入利息方程后测量他们必须支付的总金额。我遇到了两个问题,我已经弄乱了几个小时,但由于某种原因无法弄清楚。最大的问题是,在插入变量后应该计算贷款总支付额的类,但它总是返回零,我不明白为什么。是不是语法有问题?我创建了一个测试贷款类来测试该程序,该程序创建十个具有十个随机时间长度的随机贷款,并且“totalPay”和“monthlyPay”(取决于totalPay)始终为零。
第二个问题是我试图根据贷款的年数对十笔随机贷款进行排序,但我无法让它工作!我尝试了几种排序方法,我包含的方法是最新的,也可能是最愚蠢的方法哈哈哈,但这是我最近使用的方法。我已经包含了下面的所有代码,有什么想法吗?
贷款类别: (有点长,但重要的是主要贷款类别,totalPayment和monthlyPayment)
public class Loan {
double annualInterestRate = 2.5;
int numberOfYears = 1;
double loanAmount = 1000;
double base;
double exponent;
double totalPay;
String summary;
double monthly;
String[] list = new String[10];
String s;
/**
* creates default loan with 2.5 annual interest rate 1 year and 1000$
*/
public Loan(){
}
/**
* totalPay = amount(1+rate/12)^(year*12)
*
* @param anualInterestRate
* @param numberOfYears
* @param loanAmount
*/
public Loan(double anualInterestRate, int numberOfYears, double loanAmount){
base = (double) ( loanAmount * (1+anualInterestRate/12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
/**
*
* @return total payment
*/
public double totalPayment(){
return this.totalPay;
}
/**
*
* @return Monthly Payment
*/
public double monthlyPayment(){
monthly = (totalPay/12);
return monthly;
}
}
测试贷款:
import java.util.Random;
public class TestLoan {
public static void main (String[] args){
Random r = new Random();
Loan[] list = new Loan[10];
for (int i = 0; i < 10; i++){
Loan x = new Loan();
list[i] = x;
System.out.println(list[i].toString());
}
System.out.println();
System.out.println();
for (int i = 0; i < 9; i++){
list[i].setNumberOfYears(r.nextInt(30));
if (list[i].getNumberOfYears() > list[i+1].getNumberOfYears())
list[i] = list[i+1];
System.out.println(list[i].toString());
}
}
}
感谢您的浏览!
编辑删除了不相关的代码
最佳答案
您设置了年数,但您从未计算基数、指数或总支付额。这种情况只会发生在您从未调用过的构造函数中。
您需要做的是将功能代码从构造函数移出并移入计算方法。该构造函数应该用于构造对象。
旧构造函数:
public Loan(double anualInterestRate, int numberOfYears, double loanAmount) {
base = (double) (loanAmount * (1 + anualInterestRate / 12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
更好的方法:
public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
}
public void calculatePay() {
base = (double) (loanAmount * (1 + annualInterestRate / 12));
exponent = (double) (numberOfYears * 12);
totalPay = (double) Math.pow(base, exponent);
}
此外,您的排序方法也有缺陷。您应该确定 Loan
的良好自然排序是什么,然后实现 Comparable
接口(interface)。
然后您可以使用现有的排序库,如下所示:
for (int i = 0; i < 9; i++) {
list[i].setNumberOfYears(r.nextInt(30));
list[i].calculatePay();
}
Arrays.sort(list);
for (Loan loan: list) {
System.out.println(loan);
}
关于java - 类不会计算它应该计算的内容,也是 : sorting arrays of objects?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23305769/