我尝试使用通过HTML表单提交的值计算月度汽车贷款,这些值传递给使用Java类提供答案的servlet。每次我运行表单时,我都会得到NaN。
表格:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Car Loan</title>
</head>
<body>
<h1>Car Loan Calculator</h1>
<form method = "get" action = "CalcPayment">
<label> APR: </label><input type ="text" name ="apr"><br>
<label> Term (in years): </label><input type ="text" name
="term"><br>
<label> Principal: </label><input type ="text" name
="principal"><br>
<input type="submit" value ="Get Loan Payment">
</form>
<p>
Loan payment is: ${carLoan.getPayment()}
</p>
</body>
</html>
的Servlet
@WebServlet(name = "CalcPayment", urlPatterns = {"/CalcPayment"})
public class CalcPayment extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String strApr = request.getParameter("apr");
String strTerm = request.getParameter("term");
String strPrincipal = request.getParameter("principal");
int apr, term;
double principal;
CarLoan loanPay;
apr = Integer.parseInt(strApr);
term = Integer.parseInt(strTerm);
principal = Double.parseDouble(strPrincipal);
loanPay = new CarLoan (apr, term, principal);
request.setAttribute("carLoan",loanPay);
request.getRequestDispatcher("/index.jsp").forward(request,
response);
}
}
对象:
package pojos;
public class CarLoan {
private int apr, term;
private double principal;
public CarLoan (){
this.apr = 0;
this.term = 0;
this.principal = 0;
}
public CarLoan(int apr, int term, double principal) {
this.setApr(apr);
this.setTerm(term);
this.setPrincipal(principal);
}
public double getApr() {
return apr;
}
public void setApr(int apr) {
if(apr >= 0 && apr <= 30){
this.apr = apr;
}
else{
throw new IllegalArgumentException("APR must be between 0 and
30");
}
}
public double getTerm(){
return term;
}
public void setTerm(int term) {
if(term>=1 && term<=6){
this.term = term*12;
}
else{
throw new IllegalArgumentException("Loan term must be between 1
"
+ "and 6");
}
}
public double getPrincipal(){
return principal;
}
public void setPrincipal(double principal) {
if(principal>=0){
this.principal = principal;
}
else{
throw new IllegalArgumentException("Principal amount cannot be
+ "negative");
}
}
public double getPayment(){
double r = ((this.apr/100)/12);
double denominator = (Math.pow(1+r, this.term) - 1);
double numerator= (r * Math.pow(1 + r, this.term));
return (numerator/denominator);
}
@Override
public String toString() {
return String.format("rate= %d term=%d principal=%.2f", this.apr,
this.term, this.principal,+ this.getPayment());
}
}
答案 0 :(得分:0)
我认为问题出在getPayment()的最后一行。如果分母和分子都是0.0,则会出现NaN错误。
您可以通过暂时返回固定值来尝试,以查看NaN错误是否仍然存在。