Click to See Complete Forum and Search --> : Random


sypress
10-01-2009, 01:29 PM
I have an array of integers like this:

int numbers[] = {1,2,3,4,5};

I want to pick a number from the array randomly. How is it done?

nspils
10-04-2009, 11:32 PM
I take it that you are going to randomly choose which element to display [rather than randomly choosing among the content of the array which would be more problematic]. You want to use an object which generates random ints with a lower bound of 0 and an upper bound of 4.

A way to do this is to create random number generator using the Random class. You initialize the generator using the constructor - you can use a seed of a number of the long datatype (such as time) to create random number sequences. So you could use a declaration:


Random myInts = new Random();
or
Date myDate = new Date();
Random myRandomInts = new Random( myDate.getTime() ); /// this is seeded with the current time, which is a long value


The Random generator returns doubles between 0.0 and 1.0. You can code the conversion of this double to an int constrained to 0 to 4, or you could use the nextInt() method of the Random class (take a look at the JDK, which describes this method as "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence."). Since the numbers returned would be exclusive of 5, the largest value you'll get will be 4.


Int nextElement;
nextElement = myRandomInts.nextInt( 5 );


The returned int "nextElement" is then the element you want to read/use.

sypress
10-05-2009, 04:31 AM
Thanks :)
A new problem with a thread has occured. I move to a class that has a thread which shows an animation. I want the thread to start when the class is entered and run a loop of the animation and then stop. This is J2ME so threading is a bit more difficult (at least to me). My code works in a very strange way and it never stops.



public class It extends Canvas implements Runnable{
private Midlet midlet;
private boolean running = false;

private int i = 0;
private int n = 4;
private Image img[] = new Image[n];

public It(Midlet m){
this.midlet = m;
try {
img[0] = Image.createImage("/pic1.PNG");
img[1] = Image.createImage("/pic2.PNG");
img[2] = Image.createImage("/pic3.PNG");
img[3] = Image.createImage("/pic4.PNG");
}catch (IOException e) {
}
}

protected void paint(Graphics g){
running = true;
Thread th = new Thread(this);
th.start();
g.drawImage(img[i], getHeight()/2, getWidth()/2, Graphics.HCENTER|Graphics.VCENTER);
}

public void run(){
while(running){
System.out.println(i);
try {
i++;
if(i >= n){
i = 0;
running = false;
}
else{
Thread.sleep(500);
repaint();
}
}catch(Exception e){}
}
}
}

sypress
10-05-2009, 05:02 AM
Just solved it. I could just kick myself.

public void run(){
while(running){
System.out.println(i);
try {
i++;
if(i >= n-1){
running = false;
}
else{
Thread.sleep(500);
repaint();
}
}catch(Exception e){}
}
}