# problem on Math.random()

Lalit Sha
Greenhorn
Posts: 28
Can anybody help me with this problem. Write a program which generates 5 random int values. Using an if-else statement each value is tested whether its greater than, less than or equal to a second randomly generated value.( No using arrays in this problem). I have written a program for this. I would like to know whether it is correct. Thanks .

public class GenerateRandonInt {
public static void main(String[] args) {
int r1, r2;
for(int i = 1; i <= 5; ) {<br /> r1 = (int)Math.random();<br /> r2= (int)Math.random();<br /> i = i+2;<br /> System.out.println(r1);<br /> System.out.println(r2);<br /> if (r1 > r2)
System.out.println("r1 > r2");
else if (r1 < r2)
System.out.println("r1 < r2");
else
System.out.println("r1 == r2");
}
}
}

Manfred Leonhardt
Ranch Hand
Posts: 1492
One problem jumps right out: the Math.random method returns a value between 0. and 1.. Using your code you will never get anything but 0 as your integers. You need to multiply the Math.random result with a number (preferably >= 100).
Since this is a beginner forum, I will tell you that you should get used to places braces for all if and else blocks to avoid later confusion. It doesn't cost much and will be very helpful throughout your career in programming.
The example below is your new code. I interpretted the instructions slightly different from you because I only create the comparison integer once before looping instead of everytime inside the loop. Whichever way you go don't forget those braces ... code maintainers everywhere will thank you!

Manfred.

Grant Crofton
Ranch Hand
Posts: 154
This is generally OK, but if you run it you'll find that
a) the number is always 0, and
b) you only get 3 results.
a) is because Math.random returns a double between 0 and 1 - when you cast this to an int, it always rounds down to 0.
You can either multiply the number before you cast it, like
int i = (int)(Math.random()*100);
or use doubles instead of ints.
b) is because you are adding 2 to i each time instead of 1. Also, you usually do this in the for statement, like
for( int i=0; i<5; i++ ).<br /> (i++ means i=i+1, if you didn't know).<br /> Here is the working code:<br />
Hope that helps.

Grant Crofton
Ranch Hand
Posts: 154
I had a feeling that would happen...

Manfred Leonhardt
Ranch Hand
Posts: 1492
By the way, since you are using integer random numbers you can use the Random class in java.util. My example above using the Random class:

The 1000 paremeter to rand.nextInt is just so that the returned integer is positive and less than 1000.
Manfred.