Click here to Skip to main content
Click here to Skip to main content

Tagged as

Random Number Game using J2ME

, 18 Jul 2011
Rate this:
Please Sign up or sign in to vote.
Developing a random number game using J2ME technology

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Sample Image - maximum width is 600 pixels

Introduction

This article is a demonstration of developing a random number game using Java2 Microedition Platform (J2ME). This article will give a brief idea about how simple it is to develop useful applications using J2ME. It is not an in-depth discussion on J2ME. It is assumed that the reader has working knowledge of programming in Java language.

Background

J2ME is a Java-based platform for developing applications capable of running on small devices, most commonly, mobile phones. Using J2ME, anyone can easily develop useful Java applications to be run on mobile devices. These applications are called MIDlets and are managed by a software called application-management software (AMS) built in a mobile device. A J2ME application is executed on an emulator. When a J2ME application is built it creates two files, one with extension JAR and another with extension JAD. The JAR file is an archive containing the MIDlet class and JAD file is a descriptor file which describes the JAR file. The application can be executed on a Java enabled mobile device by copying the two files to the device.

A MIDlet undergoes through the following states in its life cycle:

  • Paused
  • Started
  • Destroyed

The initial state is the paused state. The AMS activates the midlet and calls its startApp() method causing it to move to the started state. The destroyApp() method is called to destroy the midlet. A boolean parameter is passed to the destroyApp() method to indicate whether the destruction is unconditional or optional. Optional destruction can be cancelled by throwing a MIDletStateChangeException.

Using the Code

There are two main packages, javax.microedition.midlet and javax.microedition.lcdui, which are required in every MIDlet. In J2ME, the abstract Display class represents the main display screen and the form class represents one of many forms which can be displayed on the screen. Processing commands can be implemented by implementing the CommandListener interface. The CommandListener interface declares the commandAction() method which must be implemented by the MIDlet class.

package azim;			// Main package

import javax.microedition.midlet.*;	// Contains definition for the MIDlet class
import javax.microedition.lcdui.*;	// Contains definition for common 
				// user interface elements
import java.util.*;		// For the Random class

public class RandomMidlet extends MIDlet implements CommandListener
{

    Form form;				// Represents the main form
    Display display;			// Represents the main display screen
    TextField txtNumber			// Text field to accept input from user.
    Command cmdCheck,cmdExit,cmdAbout;	// Commands to perform processing
    int x,ctr;				// Number and counter

The startApp() method is used to create the user interface for the MIDlet and register the commandListener. The nextInt() method from the Random class returns a value between 0 and the parameter passed to it.

public void startApp()
{
    x=new Random().nextInt(101);			// Generating a random number
    ctr=0;					// Initializing the counter
    form=new Form("Number Guess Game");		// Initializing the form with title
    display=Display.getDisplay(this);		// Initializing the display
    txtNumber=new TextField("Enter a number 
		(Between 0 and 100)", "", 10, TextField.NUMERIC);
						// Accepting number
    cmdCheck=new Command("Check",Command.OK,1);	// Initializing command
    cmdExit=new Command("Exit",Command.EXIT,3);	// Initializing command
    cmdAbout=new Command("About",Command.HELP,4);	// Initializing command
    form.append(txtNumber);			// Adding TextField on form
    form.addCommand(cmdCheck);		// Adding Command
    form.addCommand(cmdExit);		// Adding Command
    form.addCommand(cmdAbout);		// Adding Command
    form.setCommandListener(this);		// Adding Command
    display.setCurrent(form);		// Displaying Form
}

Implementing the other life cycle methods.

public void pauseApp()
{
}

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

Implementing commandAction() method. The commandAction() method receives two parameters. The Command parameter denotes the source command which initiated the process and the Displayable parameter denotes the object on which the event occurred.

An Alert object is used to display a message in a dialog box. The first parameter of the Alert constructor is the title. The second parameter is the message to be displayed. The third parameter represents the image to be displayed. The fourth parameter is the alert type.

public void commandAction(Command c,Displayable d)
    {
        if(c==cmdCheck)				// Check command was selected
        {
            if(txtNumber.getString().trim().length()==0)// Return if no input given
            {
                return;
            }
            Alert alert=null;
            int n=Integer.parseInt(txtNumber.getString());// Get number entered by user
            ctr++;					// Increment counter
            if(n<x)
            {
                alert=new Alert("Not quite","Try a larger value ",null,AlertType.WARNING);
		// Show error if entered number is less than the guessed number
            }
            else if(n>x)
            {
                alert=new Alert("Not quite","Try a smaller value ",null,AlertType.WARNING);
		// Show error if entered number is greater than the guessed number
            }
            else
            {
                alert=new Alert("You got it","Congrats!!! 
		You have made it in "+ctr+" attempts.",null,AlertType.INFO);
			// Show success message if entered number is equal to 
			// the guessed number
                x=new Random().nextInt(101);	// Generate new random number
                ctr=0;			// Reset counter
            }
            alert.setTimeout(Alert.FOREVER);  // Specify alert to be displayed until closed.
            display.setCurrent(alert);	// Display alert
        }
        if(c==cmdExit)
        {
            destroyApp(true);		// Destroy MIDlet if Exit command selected
        }
        if(c==cmdAbout)
        {
            Alert alert=new Alert("About Random Game",
			"Programmed by Azim",null,AlertType.INFO);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);	// Display About information
        }
    }
}

Points of Interest

I have used Java(TM) ME Platform SDK 3.0 to develop this application. Other environments like Netbeans and Sun Java (TM) Wireless Toolkit 2.5.2_01 for CLDC can also be used to develop J2ME applications. When the application is run, the output is displayed on the emulator. The application can be executed on a Java enabled mobile device by copying the generated JAD and JAR files to the device.

History

  • 15th July, 2011: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Azim Zahir
Instructor / Trainer NIIT, India
India India
I am a trainer by profession. Currently I am working with NIIT (Mumbai, India) as a Senior Faculty. I enjoy programming as a hobby. My favorite technologies are Flash, Flex and Silverlight.
 
Of late I have developed keen interest in WPF and Windows Mobile programming.
 
Apart from computers, my favorite pastime is bicycling.

Comments and Discussions

 
GeneralMy vote of 3 PinmemberFiro Atrum Ventus27-Jul-11 17:39 
GeneralRe: My vote of 3 PinmemberAzim Zahir30-Jul-11 17:20 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 18 Jul 2011
Article Copyright 2011 by Azim Zahir
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid