Thursday, 6 December 2012

Generating Random Numbers

     Random numbers will help you add an element  of unpredictability to your website.you can retrieve a random number and display a corresponding image, tip, or greeting.you must first create a random object  and then call the nextInt method to return a random number.

Example:

<%@page import="java.util.*" %>
<html>
<head>
<title>Generating Random Numbers</title>
</head>
<body>
<h3>Random Numbers:</h3>
<%!
Random randomValue=new Random();
%>
<p>
Random Number:<%=randomValue.nextInt() %>
<br>
Positive Random Number:<%=Math.abs(randomValue.nextInt()) %>
<br>
Generating a random Number between 1 and 6 :<%=(Math.abs(randomValue.nextInt())%5)+1 %>
<p>
<b>Note:</b>Each time this script is run a different output will be produced.
</body>
</html> 

Description:


  • Use the import page directive to import the java.util package.The Random class is located in this package.
  • Create a random object instance.
  • Call the nextInt method.The nextInt method will return a random number anywhere within the full range of integer values.Be aware that the nextInt method can return a negative number.
  • Pass the generated random number to the abs method.This will convert all generated numbers from negative to positive.
  • Use the modules operator to calculate the remainder between a positive random number and the maximum random number that you require.Add one to this result.


*****************************OUTPUT***************************************

Random Numbers:

Random Number:443353488
Positive Random Number:1446394622
Generating a random Number between 1 and 6 :2

Note:Each time this script is run a different output will be produced.
****************************************************************************



2 comments: