Dice Roller

We are going to make one program on the dice roller in which the number in the dice will be selected randomly.

Dice Roller

Dice Roller

     

We are going to make one program on the dice roller in which the number in the dice will be selected randomly. 

To make a program over this firstly we need to make a class DiceRoller in which we will have a doGet() method in which we will have our application logic. To make the dice working randomly use the random() method of the class java.lang.Math. To print the number on the browser call the method getWriter() of the response object which will return the PrintWriter object. Now by the object of the PrintWriter class print the values of the dice on the browser. 

The code of the program is given below:

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

public class DiceRollerServlet extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse
  response
)throws ServletException, IOException{
  PrintWriter pw = response.getWriter();
  String dice1 = Integer.toString((int)(Math.random()*6)+1);
  String dice2 = Integer.toString((int)(Math.random()*6)+1);
  pw.println("<html><body>");
  pw.println("dice roller<br>");
  pw.println("dice1 value is " + dice1 + " and <br>dice2 value is " 
 
+dice2);
}
}

XML File for this program:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
 PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
 <servlet>
 <servlet-name>Zulfiqar</servlet-name>
 <servlet-class>DiceRollerServlet</servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>Zulfiqar</servlet-name>
 <url-pattern>/DiceRollerServlet</url-pattern>
 </servlet-mapping>
</web-app>

The output of the program is given below:

Download this example: