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开发者_如何学JAVA.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");
}
Math.random()
returns a double between 0
and 1
. Casting to int
will always truncate to 0
.
If you want a random integer use the Random.nextInt(range)
method.
Are you sure that (int) Math.random()
always returns 1? If you told us that it always returns 0, I would believe that immediately.
Math.random()
returns a double
in the range [0;1)
. The conversion from double
to int
truncates the number, to it is always 0.
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.
Math.random()
returns a double
>= 0 and < 1. If you want a random number between 0 and x, use (int)(Math.random() * x)
.
Because Math.random returns a value between 0 and 1 (either double or float I guess). Casting it to an int it loses the value after the decimal point and I guess casting rounds up to 1.
The correct way to use Math.Random() is to multiple it by the uppermost number that you want, then close the parenthesis and cast it to an int (if needed)
int randomNumber = (int)(Math.random()*max)
Its the placement of the parenthesis that you are off on. Math.random is a great function to use when you have an upper bounds for the range of numbers that you want. There is another stack overflow answer on getting it to work with a lower bounds as well, for a range of numbers from a min to a max.
Click here: Math.random() explained
My Math.random() method always return with 1
Well, this isn't true- in that case it always returns 0, which is used as num but what happens next:
b[x]=a[num];
you call a[0] three times as b[0], b[1] and b[2] and since you hardcoded
a[0]=1;
you'll get only that value. In given example you can try
num=(int)(Math.random()*3);
as it simply generates random int from 0 to 2 or even use
num=(int)(Math.random()*a.length);
I'm not a Java programmer but I have some idea of it.
Math.random() will produce random numbers between 0 and 1. Casting to int means you want either 1 or 2.
Since you are getting only 1, Math.random() just happens to be producing numbers between 0.5 and 1, that's all.
I also know that if you run the program again and again, it will produce the same set of pseudorandom values (except maybe you recompile).
精彩评论