Monday, July 21, 2008

Generate Random number in j2ME

As there is no package named Math in javaME , we can not use the method Math.Random . So its a question 'How to generate random number in Midlet?'.

The solution is :
SOURCE CODE:

Random generator = new Random();
generator.setSeed(System.currentTimeMillis());
float f = generator.nextFloat();

2 comments:

ss said...

code is good

Anonymous said...


package numberslearner;

import java.util.Random;
import javax.microedition.midlet.*;

/**
* @author Adil
*/
public class NumberMidlet extends MIDlet {


private static int no = 10;
private static boolean isRandom;
private static int num;

public void startApp() {




}

public void pauseApp() {


}

public void destroyApp(boolean unconditional) {
}



public static String getRandomNumber(){
// int [] numbers = {1,2,3,4,5,6,7,8,9,10};
return String.valueOf(getJ2MERandom());
}


public static String getNumber(){
no = ++num;
return String.valueOf(num);
}

/***
* CDLC 2.0 and less complaint random number generator
* @return
*/
private static int getJ2MERandom() {
Random random = new Random();
int ran = Math.abs(random.nextInt());//This creates the random number...
int number = 1 + ran % no;//This is how you can use it.
return number;
}
}


adilsec at yahoo

search engine

Custom Search