previous | start | next

For Loop Example (cont.)

    1   import java.util.Random;
    2   
    3   public class RandomTester {
    4   
    5     public static void main(String[] args) {
    6       Random r = new Random();
    7       final int NGEN = 1000;
    8       final int TOPVALUE = 100;
    9       int count = 0;
   10       int n;
   11   
   12       // Generate NGEN random numbers, each in the range 1 to TOPVALUE 
   13       for(int i = 0; i < NGEN; i++ ) {
   14         n = r.nextInt(TOPVALUE) + 1;
   15         if ( n <= TOPVALUE/2 ) {
   16           count++;
   17         }
   18       }
   19       System.out.printf("Of %d random numbers, each in the range 1 to %d\n" +
   20           "%d were less than or equal to %d", NGEN, TOPVALUE, count, TOPVALUE/2);
   21     }
   22   
   23   }


previous | start | next