Pavithra
Pavithra

Reputation: 63

How to insert an element in an array in java

I am learning array concept in java. Please help to resolve the below problem.

Using the below code, i was able to print only the entered values and it's not storing the previously entered values.I want to use Array to add elements and print the same in my problem statement. I should not use ArrayList

Main Class:
    System.out.println("Enter the array value");
    int value = scan.nextInt();
    scan.nextLine();
    arrayobj.add(value);

Array Class:
   Integer array[] = new Integer[100];
public void add(Integer value){
    for(int i=0;i<1;i++)
    {
      array[i] = value;
      i++;
    }
    System.out.println("The values are");

    for(Integer a : array)
    {
        if(a!=null)
        {
             System.out.println(a);
        }
    }
}

Sample Input and Output :

    Enter your choice
    1.Add
    2.Remove
    3.Search
    1
    Enter the array value
    1
    The values are
    1
    Do you want to continue[Yes/No]
    Yes
    Enter your choice
    1.Add
    2.Remove
    3.Search
    1
    Enter the array value
    2
    The values are
    1
    2

Upvotes: 1

Views: 3066

Answers (2)

Kethiri Sundar
Kethiri Sundar

Reputation: 500

Define your Array class like this and you can add maximum 100 elements for one Array object. If you want more than 100 elements to be added you have to copy the array and create a new array with more size.

public class Array{
    private int tail = 0;
    private Integer[] array= new Integer[100];

    void add(int value){
       if(tail<=100){
          array[tail++]= value;
       }
       else{
          System.out.println("Array overflow");
       }

    Integer[] getArray(){
       return array;
    }
}

Upvotes: 1

Kethiri Sundar
Kethiri Sundar

Reputation: 500

your code seems wrong since the following for loop iterates only once and replace the 0th element of the array again and again

for(int i=0;i<1;i++)
{
  array[i] = value;
  i++;
}

The length of an array is immutable in java. This means you can't change the size of an array once you have created it. If you initialized it with 2 elements, its length is 2. You can however use a different collection.

List<Integer> myList = new ArrayList<Integer>();
myList.add(5);
myList.add(7);

And with a wrapper method

public void addMember(Integer x) {
    myList.add(x);
};

You can print the list using the following function by avoiding loops

System.out.println(Arrays.toString(myList.toArray()));

Upvotes: 1

Related Questions