FahmidasClassroom

Learn by easy steps

Random

Java has random() function to generate random number for different programming purposes. The way of using random number in java has been shown in this tutorial. Follow the steps properly to create a Java GUI application by using random number.

Pre-requisites:

1. Install the latest version of JDK.

2. Install the NetBeans editor

step-1:

Create a new Java project named randomNumber without class.

Step-2:

Add a class with a JFrame. Add a label and a button in the form. Add a Listbox, a JSpinner, and two buttons in the jFrame.

Step-3:

Import the following packages into the aplication.

import javax.swing.DefaultListModel;
import java.util.Arrays;  

Step-4:

Declare the following variables after the class declaration.

 int arraySize;
 int[] integerArray;
 int nArray[];
 DefaultListModel listModel = new DefaultListModel();

Step-5:

Double clicks the Add button and add the following code.

arraySize =Integer.valueOf(jSpinner1.getValue().toString()).intValue();
integerArray = new int[arraySize];
listModel.clear();
        
nArray = new int[arraySize];
        
java.util.Random myRandom = new java.util.Random();
for (int i = 0; i < arraySize; i++)
{
    int s = myRandom.nextInt(arraySize);
    nArray[i]= s;
    listModel.addElement(s);    
}
jList1.setModel(listModel);

Step-6:

Double clicks the Sort button and add the following code.

int s;
listModel.clear();
Arrays.sort(nArray);
// display sorted integers
for (int i = 0 ; i < arraySize; i++)
{
    s = nArray[i];
    listModel.addElement(s);
}
jList1.setModel(listModel);
                                       

Step-7:

Run the application