gpt4 book ai didi

java - 没有发现异常吗?

转载 作者:行者123 更新时间:2023-12-01 19:11:21 25 4
gpt4 key购买 nike

我对 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;
}
}

最佳答案

如果您确实希望构造函数在某种情况下抛出异常,您应该如下所示:

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();
}

关于java - 没有发现异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8275529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com