我在这里有一个问题,我试图根据一个人的年龄计算一个人的月、周、天、小时、分钟和秒数。我正在使用 HTML 表单来获取数据(姓名和年龄)并将其发送到 servlet 以计算上述结果。问题在于,当用户提供 29 岁或以下的年龄时,结果似乎是准确的,但当用户输入 70 或以上这样的大值时,它会给出错误的秒数负值。这是我的servlet代码:
package package1;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet_Post_Example extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = "";
String $age = "";
try
{
name = request.getParameter("name");
$age = request.getParameter("age");
int age = Integer.parseInt($age);
int months = age * 12;
int weeks = age * 52;
int days = age * 365;
int hours = 24 * 365 * age;
int minutes = 60 * 24 * 365 * age;
int seconds = 60 * minutes;
out.println("<html>");
out.println(" <head>");
out.println(" <title>Servlet Get Response</title>");
out.println(" </head>");
out.println(" <body bgcolor=\"#AAFFAA\">");
out.println(" <h1>"+name+" you are approximately "+months+" months old, "+weeks+" weeks old, "+days+" days old, "+hours+" hours old, "+minutes+" minutes old and "+seconds+" seconds old!</h1>");
out.println(" <a href=\"index.html\">Click here</a> to go back to the index page.");
out.println(" </body>");
out.println("</html>");
}
catch(NumberFormatException xcp)
{
out.println("<html>");
out.println(" <head>");
out.println(" <title>Servlet Get Response</title>");
out.println(" </head>");
out.println(" <body bgcolor=\"#AAAAAA\">");
out.println(" <h1 style=\"color: red\">There was an error! You must type the a valid integer for your age! You entered "+$age+"</h1>");
out.println(" <a href=\"index.html\">Click here</a> to go back to the index page.");
out.println(" </body>");
out.println("</html>");
//xcp.printStackTrace(out);
}
finally
{
out.close();
}
}
}
该网站托管在这里。请检查一下谢谢。