com.jspcr.servlets.K2MServlet.java Source code

Java tutorial

Introduction

Here is the source code for com.jspcr.servlets.K2MServlet.java

Source

/**
*  Copyright (c) 2002 by Phil Hanna
*  All rights reserved.
*  
*  You may study, use, modify, and distribute this
*  software for any purpose provided that this
*  copyright notice appears in all copies.
*  
*  This software is provided without warranty
*  either expressed or implied.
*/
package com.jspcr.servlets;

import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
* Prints a conversion table of miles per gallon
* to kilometers per liter
*/
public class K2MServlet extends HttpServlet {
    /**
    * Numeric format used to display temperatures
    */
    private static final DecimalFormat FMT = new DecimalFormat("#0.00");

    /**
    * Factor to convert from km/l to mi/gal
    */
    private static final double CONVERSION_FACTOR = 2.352145;

    /**
    * Handles a GET request
    */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Set up for creating HTML output

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        // Generate heading

        out.println("<html>" + "<head>" + "<title>Fuel Efficiency Conversion Chart</title>" + "</head>" + "<body>"
                + "<center>" + "<h1>Fuel Efficiency Conversion Chart</h1>"
                + "<table border='1' cellpadding='3' cellspacing='0'>" + "<tr>" + "<th>Kilometers per Liter</th>"
                + "<th>Miles per Gallon</th>" + "</tr>");

        // Generate table

        for (double kmpl = 5; kmpl <= 20; kmpl += 1.0) {
            double mpg = kmpl * CONVERSION_FACTOR;
            out.println("<tr>" + "<td align='right'>" + FMT.format(kmpl) + "</td>" + "<td align='right'>"
                    + FMT.format(mpg) + "</td>" + "</tr>");
        }

        // Generate footer

        out.println("</table>" + "</center>" + "</body>" + "</html>");
    }
}