Servlet Program to find the factorial of a given number.
i)HTML form to input a given number
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Factorial of Number</h1>
<form action="MyServlet" method="Get">
Enter the Number:<input type="text" name="n1"/><br/>
<input type="submit" value="Find"/>
</form>
</body>
</html>
ii) Servlet Program to accept the given number convert to integer and find the factorial of a number and result is sent back to the Client.
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 MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String x=request.getParameter("n1");
int n=Integer.parseInt(x);
int i=1,fact=1;
if(n==0)
{
out.println("<h1>factorial of 0"+"is"+n+"</h1>");
}
else
{
while(i<=n)
{
fact=fact*i;
i=i+1;
}
out.println("<h1>factorial of " + n +"="+fact+ "</h1>");
}
}
}
No comments:
Post a Comment