Servlet年龄计算器给出了错误的结果

时间:2013-11-02 15:19:33

标签: java servlets

我在这里遇到问题,我试图根据个人的年龄来计算一个人的月,周,日,小时,分钟和秒的数量。我使用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();
        }
    }
}

该网站已托管here.,请查看谢谢。

2 个答案:

答案 0 :(得分:3)

此行int minutes = 60 * 24 * 365 * age;int seconds = 60 * minutes;可能会超出Integer.MAX_VALUE的限制。将分钟和秒声明为long

long minutes = 60L * 24 * 365 * age;// Add L for long
long seconds = 60 * minutes;

答案 1 :(得分:0)

您需要将分钟和秒的类型更改为long。那它应该工作正常。因为任何大于2 ^ 31-1的int值都会导致溢出,并且由于此溢出是静默的,所以您得到负值。