user310000 user310000 - 5 months ago 11
Java Question

My Math.random() method always return with 1 ? WHy?

There are 3 marbles randomly generated and i'll compare them if they are same,different or one is different. My code is below and my question is above... can u help me out ?

public static void marb(){
int a[],b[];
int num=0;

a=new int[3];
b=new int[3];

a[0]=1;
a[1]=2;
a[2]=3;

**num=(int)Math.random();** //num is always assigned 1

for(int x=0;x<3;x++)
{
num=(int)Math.random();

b[x]=a[num];

System.out.println(""+x+". marble:"+b[x]);

}

int x=0;

if(b[x]==b[x+1] && b[x+1]==b[x+2])
System.out.println("ALL SAME");
else if(b[x]!=b[x+1] && b[x]!=b[x+2] && b[x+1]!=b[x+2])
System.out.println("ALL DIFFERENT");
else
System.out.println("One is different");

}

Answer

Create an instance of the random number generator

Random rand = new Random(); 

which also seeds the generator.

Then call

int myrandnum = rand.nextInt();

Subsequent calls to the nextInt method will generate a different number.