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.
Based on the statement that you provided:
You can do this way:
But you asked:
Well, when you create an array like this:
You can say that the first number is
1, but his index is actually0!It means that:
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 item1must have the index1.You can see it in the code:
I verify if
i == X - 1because if the user input1it means that he wants to change the first index, but in the code the first index is actually0and not1.