user310000 user310000 - 1 year ago 45
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];


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

for(int x=0;x<3;x++)


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");
System.out.println("One is different");


Answer Source

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.