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:

  1. <%@page import="java.util.*" %>
  2. <html>
  3. <head>
  4. <title>Generating Random Numbers</title>
  5. </head>
  6. <body>
  7. <h3>Random Numbers:</h3>
  8. <%!
  9. Random randomValue=new Random();
  10. %>
  11. <p>
  12. Random Number:<%=randomValue.nextInt() %>
  13. <br>
  14. Positive Random Number:<%=Math.abs(randomValue.nextInt()) %>
  15. <br>
  16. Generating a random Number between 1 and 6 :<%=(Math.abs(randomValue.nextInt())%5)+1 %>
  17. <p>
  18. <b>Note:</b>Each time this script is run a different output will be produced.
  19. </body>
  20. </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: