Thursday, September 16, 2010

Random in java

The expression Math.random() yields a random double number in the range zero (0.0) to one (1.0) (excluding the upper limit of exactly 1.0). You can print this value using: 
double rand = Math.random();
System.out.println(""+rand);
You can convert this to an integer in the range 1 to n using the  following code where n = 10

int n = (int)(Math.random()*10)+1;
System.out.println(""+n);

No comments:

Post a Comment

Chitika