Following is the simple program to insert, delete with a user specified index and print the element of array:
ArrayOperations.java:
--------------------------------------------------
import java.util.*;
class ArrayOperations{
public static void main (String [] args) {
Scanner scan = new Scanner (System.in);
System.out.print("Enter the Array Size: ");
final int MAX = Integer.parseInt(scan.nextLine());
Numbers nums = new Numbers(MAX);
char command;
int index;
System.out.println("To add an element into the array, type a.");
System.out.println("To delete an element from the array, type d.");
System.out.println("To print the current contents of the array, type p.");
System.out.println("To exit this program, type x.\n");
System.out.print("Add (a), delete (d), print (p) or exit (x)?:");
command = scan.nextLine().charAt(0);
while (command != ´x´) {
if (command == ´a´ || command == ´d´) {
System.out.print("Enter The index value from 0 to "+(MAX-1)+": ");
index = scan.nextInt();
scan.nextLine();
if(command == ´a´)
nums.add(index);
else
nums.delete(index);
}
else if (command == ´p´) nums.print();
else System.out.println ("Not a value input");
System.out.print("Add (a), delete (d), print (p) or exit (x)?: ");
command = scan.nextLine().charAt(0);
}
System.out.println("Program Complete");
}
}
class Numbers{
private int[] nums;
private int size;
public Numbers(int _size){
this.nums = new int[_size];
}
public void add(int index){
if (size == nums.length)
{
System.out.println("Sorry! Array is full, Value cannot be inserted.");
}
else
{
if(index == -1 || index>(nums.length-1)){
System.out.println("The index value " + index + " was not found. Please Enter valid index!");
}
else{
System.out.print("Enter the Number to be inserted at index "+index+": ");
Scanner scan = new Scanner (System.in);
int addnum = Integer.parseInt(scan.nextLine());
nums[index] = addnum;
}
}
}
public void delete(int index){
if(index == -1 || index>(nums.length-1)){
System.out.println("The index value " + index + " was not found and cannot be deleted.");
}
else{
nums[index] = 0; //set to some base case or zero
}
}
public void print(){
String output ="";
for(int str: nums){
output = output + " " + str;
}
System.out.println(output);
}
}
********************************** Output **********************************
Download this example- Click Here