我是java的新手,我遇到了一些问题,我的代码被捕获并显示异常已被捕获。如果Loan的任何值为零或更小,则代码的想法是抛出异常。下面是我的代码,它没有任何异常输出,尽管loan1和loan3只有零。任何帮助都会受到六周新手的欢迎。谢谢!
package loan;
public class Loan {
public static void main(String[] args) {
try {
Loan loan1 = new Loan(0, 0, 00.00);
Loan loan2 = new Loan(5, 10, 500.00);
Loan loan3 = new Loan(0, 0, 0.00);
}
catch (IllegalArgumentException ex) {
System.out.println(ex);
}
}
// declare variables for Loan class
double annualInterestRate;
int numberOfYears;
double loanAmount;
private java.util.Date loanDate;
// Loan class
public Loan() {
}
public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
public double getAnnualInterestRate() throws IllegalArgumentException { //exception added if value is zero or less, added on each variable
if (annualInterestRate >= 0)
throw new IllegalArgumentException("Interest rate cannot be zero or negative.");
else
return annualInterestRate;
}
public void setAnnualInterestRate(double annualInterestRate) {
this.annualInterestRate = annualInterestRate;
}
public int getNumberOfYears() throws IllegalArgumentException {
if (numberOfYears >= 0)
return numberOfYears;
else
throw new IllegalArgumentException("Number of years cannot be zero");
}
public void setNumberOfYears(int numberOfYears) {
this.numberOfYears = numberOfYears;
}
public double getLoanAmount() throws IllegalArgumentException {
if (loanAmount >= 0)
return loanAmount;
else
throw new IllegalArgumentException("Loan amount cannot be zero");
}
public void setLoanAmount(double loanAmount) {
this.loanAmount = loanAmount;
}
public double getMonthlyPayment() {
double monthlyInterestRate = annualInterestRate/1200;
double monthlyPayment = loanAmount * monthlyInterestRate / (1 - (Math.pow(1/(1 + monthlyInterestRate), numberOfYears *12)));
return monthlyPayment;
}
public double getTotalPayment() {
double totalPayment = getMonthlyPayment() * numberOfYears * 12;
return totalPayment;
}
public java.util.Date getLoanDate() {
return loanDate;
}
}
答案 0 :(得分:3)
如果你确实希望你的构造函数在某些条件下抛出异常,你应该看起来像这样:
public Loan(double annualInterestRate, int numberOfYears, double loanAmount) {
if ( annualInterestRate<0 )
throw new IllegalArgumentException( "value for anualInterestRate is too small" );
if ( numberOfYears<0 )
throw new IllegalArgumentException( "value for numberOfYears is too small" );
this.annualInterestRate = annualInterestRate;
this.numberOfYears = numberOfYears;
this.loanAmount = loanAmount;
loanDate = new java.util.Date();
}
答案 1 :(得分:1)
你只在“getter”方法中抛出一个异常,比如getAnnualInterestRate
等。但是你永远不会打电话给它们。要么调用你的一些getter,要么(更好)从构造函数和setter方法中抛出异常(因为这是你设置值的地方)。