Insertion in Array

102 Views Asked by At

I am writing a code to insert an element in an array. The expected output is that the element gets inserted in the input index by shifting the elements on the right side. I am trying to print the elements after first iteration using the nested j loop and it is giving me a NoSuchException error. To understand it better by wanting to see the list where Java errors are explained using code such as 'Scanner.java:937'. Where can I find the list and where am I doing wrong in my code ?

import java.util.*;
import java.lang.*;

public class main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int A[] = new int[N + 2];
        for(int i = 1; i <= N + 2; i++){
            A[i] = sc.nextInt();
        }
        int X = sc.nextInt();
        int Y = sc.nextInt();
        for(int i = 1; i <= N + 2; i++){
            if(i == X){
                for(int j = 1; j <= N + 2; j++){
                    A[j + 1] = A[j];
                }
                for(int j = 1; j <= N + 2; j++){
                    System.out.print(A[j]+ " ");
                }
            }
        }
    }
}

I am trying to print the elements after first iteration and want to see the list where java error are explained using code number.

2

There are 2 best solutions below

5
Diego Borba On

Based on the statement that you provided:

Write a program to input N numbers array, a number X and a number Y from user and insert an element Y in it at specified position X. X is based on 1-based indexing Note: When an element is inserted at position X, all elements that were already present at position >= X, gets shifted to one position right, not replaced.

You can do this way:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        // Array size
        int N = input.nextInt();

        // Create the array
        int[] array = new int[N];

        // Loop
        for (int i = 0; i < N; i++) {
            // Input each array element
            array[i] = input.nextInt();
        }

        // Position
        int X = input.nextInt();

        // Number to be inserted
        int Y = input.nextInt();

        // Check the position
        if (X >= 1 && X <= N + 1) {
            // New array with one extra element
            int[] resultArray = new int[N + 1];

            // Copy elements to the new array
            for (int i = 0, j = 0; i < N + 1; i++) {
                if (i == X - 1) {
                    // Insert Y at position X
                    resultArray[i] = Y; 
                } else {
                    resultArray[i] = array[j];
                    j++;
                }
            }

            // Print the array
            for (int num : resultArray) {
                System.out.print(num + " ");
            }
        } else {
            //TODO: Deal with the invalid position
        }
    }
}

But you asked:

The question says that X is based on 1-based indexing. What does that mean ?

Well, when you create an array like this:

int[] array = new int[] {1, 2, 3, 4, 5};

You can say that the first number is 1, but his index is actually 0!

It means that:

array[0] = 1
array[1] = 2
array[2] = 3
array[3] = 4
array[4] = 5

This is the 0-Based Indexing, the indexing used in programs.

So, what is 1-Based Indexing? It's the ""real life"" indexing. It means that the item 1 must have the index 1.

You can see it in the code:

if (i == X - 1) {
    // Insert Y at position X
    resultArray[i] = Y; 
}

I verify if i == X - 1 because if the user input 1 it means that he wants to change the first index, but in the code the first index is actually 0 and not 1.

0
WJS On

First here are a few places you are going wrong:

  • you need to allocate a new array to hold the original values plus the inserted one. Otherwise, you will either throw an exception as arrays do not grow dynamically as needed but must be copied.
  • The following loop cascades the value at A[j] to the end of the array, overwriting previous values.
    for(int j = 1; j <= N + 2; j++ ){
              A[j + 1] = A[j];
    }

And as mentioned in the comments, using meaningful names helps document the code. (e.g. You defined X and Y but never used Y so it wasn't immediately clear what they were for).

Here is an alternative approach. I recommend using an initialized array to facilitate testing. Prompting for array input can be done later when the code is working as expected.

int[] items = {1,2,3,4,5,6,7,8,9,10};
int n = items.length;

int location = sc.nextInt();
int itemToInsert = sc.nextInt();

if (location >= items.length + 1 || location < 0) {
    System.out.println("Invalid location.");
} else {

    // copy up to the location point
    int[] newItems = new int[items.length + 1];
    for (int i = 0; i < location; i++) {
        newItems[i] = items[i];
    }
    // insert the new value
    newItems[location] = itemToInsert;

    // append the remaining values.
    for (int i = location; i < items.length; i++) {
        newItems[i + 1] = items[i];
    }
    System.out.println(Arrays.toString(newItems));
   
}
  • First, there is nothing wrong with your approach once you get the indices et al, corrected.
  • The above, imo, has the following advantages.
    • it is simpler and doesn't iterate more than the alternative.
    • it doesn't need to test for the insertion point.
    • and it caters to inserting before the first element and after the last element. But that is an implementation decision.