0
Javaクラスを使用するサーブレットに渡されるHTMLフォームを使用して送信された値を使用して毎月の自動車ローン支払いを計算しようとしています答えをつけて私がフォームを実行するたびに、結果としてNaNが得られます。HTMLフォーム(Java)の変数を使用して計算を実行すると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>
サーブレット:
@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());
}
}
コードのどの行でNaNを取得し、その時点でどの入力を使用したかを教えてもらえれば、簡単にお手伝いできます。 – DanielBarbarian