Implementing the Stipend Calculator

Using JDeveloper, begin by creating a new application:

Create a project within the application (A JDeveloper application may consists of multiple projects):

Add a servlet to the application:

Add a web page to the project:

The web page contains the form shown earlier. It posts an HTTP request containing the parameters age, years, and income (from the form) to the calculator servlet.

Here is the doPost method for the servlet:

    public void doPost(HttpServletRequest request,
                       HttpServletResponse response) throws ServletException, IOException {
        response.setContentType(CONTENT_TYPE);
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Calculator</title></head>");
        out.println("<body>");
       
        int age = new Integer(request.getParameter("age"));
        double income = new Double(request.getParameter("income"));
        int years = new Integer(request.getParameter("years"));
       
        double stipend = calcAmount(age, income, years);
       
        out.println("You could qualify for $" + stipend + "/month");
       
        out.println("</body></html>");
        out.close();
    }

The calcAmount method encodes the following business rules:

1. stipend recipients must be over 65

2. stipend recipients must have an anual income no more than $50,000

3. stipend recipiants must have had at least 10 years of service to the organization

4. The monthly stipend will be F1 * F2 * F3 * 1500

where:

   F1 = (age – 65)/10

   F2 = (50000 – income)/30000

   F3 = (years – 10)/10

Here's the implementation:

    private double calcAmount(int age, double income, int years) throws ServletException {
       if (age < 0 || income < 0 || years < 0) {
           throw new ServletException("inputs must be > 0");
       }
        double result = 1500.0;
        if (age < 65) {
            result = 0;
        } else if (age < 75) {
            result *= (age- 65)/10.0;
        }
       
        if (50000 < income) {
            result = 0;
        } else if (20000 < income) {
            result *= (50000 - income)/30000;
        }
       
        if (years < 10) {
            result = 0;
        } else if (years < 20) {
            result *= (years - 10)/10.0;
        }

        return result;
    }