Rolling Dice Example

Rolling Dice Example


Posted in : Java Posted on : June 20, 2011 at 11:32 AM Comments : [ 0 ]

In this section we will discuss how the dice rolled randomly on the web page in servlet in java.

Rolling Dice Example

In this section we will discuss how the dice rolled randomly on the web page in servlet in java.

The example given below is explaining that the rolling of dice randomly. To accomplish this problem I used Math.random() method. This method returns a random number by executing each time.

Example :

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

public class RollingDice extends HttpServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException{
PrintWriter out = res.getWriter();
int dice1, dice2,total;
dice1= (int)(Math.random()*6)+1;
dice2= (int)(Math.random()*6)+1;
out.println("<html><body>");
out.println("<h2>Dice roller</h2><br>");
out.println("<font size=5>Value of dice1 = " + dice1 + "<br>" +
"Value of dice2 = " +dice2+"<br>");
total=dice1+dice2;
out.println("total dice value is = "+total);
out.println("</font></body></html>");
}
}

XML mapping (web.xml)

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>bipul5</servlet-name>
<servlet-class>RollingDice</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>bipul5</servlet-name>
<url-pattern>/RollingDice</url-pattern>
</servlet-mapping>
</web-app>

Output : When you will execute the program the following output will be shown

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 

 
Tutorial Topics