J2ME Random Number

In this application we are going to generate the random number using Random class.

J2ME Random Number

J2ME Random Number

     

In this application we are going to generate the random number using Random class. The Random class within the java.util package and we can use it by importing the java.util.Random package. 

public void random(){
  Random number = new Random();
  float f = number.nextFloat();
  number.setSeed(System.currentTimeMillis());
  item.setText(""+(f*100.0f)%100);
}

In the above source code nextFloat returns the next pseudorandom, uniformly distributed float value from this random number generator's sequence and the setSeed method is used to sets the seed of this random number generator using a single long seed and finally by the using of canvas class we have to display the random number on the mobile window.

The Application is as follows:

 

RandomNumber.java 

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

public class RandomNumber extends MIDlet implements CommandListener{
  private Display display;
  private Command exit, generate;
  private StringItem item;
  private Form form;

  public RandomNumber(){
  display=Display.getDisplay(this);
  form = new Form("RandomNumber");
  exit = new Command("Exit", Command.EXIT,0);
  generate = new Command("Generate", Command.OK,1);  
  item = new StringItem("Number ","");
  form.addCommand(exit);
  form.addCommand(generate);
  form.setCommandListener(this);
  form.append("This Random Number Generated By Mr. Sandeep Kumar Suman,
 Software Developer, Roseindia Technology Pvt Ltd. Mobile No:+919313985248");
  form.append(item);
  }

  public void startApp(){
  display.setCurrent(form);
  }

  public void pauseApp(){}

  public void destroyApp(boolean unconditional){
  notifyDestroyed();
  }

  public void commandAction(Command c, Displayable d){
  String label = c.getLabel();
  if(label.equals("Exit")){
  destroyApp(false);
  }else if(label.equals("Generate")){
  random();
  }
  }

  public void random(){
  Random number = new Random();
  float f = number.nextFloat();
  number.setSeed(System.currentTimeMillis());  
  item.setText(""+(f*100.0f)%100);
  }
}

Download Source Code