Create array of random size


 

Create array of random size

In this tutorial, you will learn how to create a randomly sized integer array.

In this tutorial, you will learn how to create a randomly sized integer array.

Create array of random size

In this tutorial, you will learn how to create a randomly sized integer array. For this, we have declared an array and using the Random class, we have set the random size to array. We have stored the elements randomly into the array. Then to perform an operation on this array, we have create a text field to enter any index of array and another textfield to display the array element at the specified index. A button is created to cause the array element to be displayed. If the index entered by the user is exceeds the size of array, the code catch out-of-bounds exceptions and display "Out Of Bounds" in the array element field.

Example:

import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;

class ShowElement extends JFrame{
JButton ADD;
JPanel panel;
JLabel label1,label2;
final JTextField text1,text2;
ShowElement(){
label1 = new JLabel();
label1.setText("Enter Index:");
text1 = new JTextField(20);

label2 = new JLabel();
label2.setText("Element at specific Index:");
text2 = new JTextField(20);

ADD=new JButton("Show Element");

panel=new JPanel(new GridLayout(3,2));
panel.add(label1);
panel.add(text1);
panel.add(label2);
panel.add(text2);
panel.add(ADD);
add(panel,BorderLayout.CENTER);
Random r=new Random(); 
final int size=r.nextInt(50)+1;
final int arr[]=new int[size];
for(int i=0;i<arr.length;i++){
int x=r.nextInt(100)+1;
arr[i]=x;
System.out.println(arr[i]);
}
ADD.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae){
try{
String value=text1.getText();
int in=Integer.parseInt(value);
if(in>=size){
text2.setText("Out of Bounds");
}
else{
int ele=0;
for(int i=0;i<arr.length;i++){
if(i==in){
ele=arr[i];
}
}

text2.setText(Integer.toString(ele));
}
}
catch(Exception e){}
}
});
}

public static void main(String arg[])
{
try
{
ShowElement frame=new ShowElement();
frame.setSize(300,100);
frame.setVisible(true);
}
catch(Exception e){
}
}
}

Ads