我正在编写一段代码来在数组中插入一个元素。预期的输出是通过将元素移动到右侧来将元素插入到输入索引中。 我试图使用嵌套 j 循环在第一次迭代后打印元素,它给了我一个 NoSuchException 错误。 为了更好地理解它,您可以查看使用“Scanner.java:937”等代码解释 Java 错误的列表。 我在哪里可以找到该列表以及我的代码哪里做错了?
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]+ " ");
}
}
}
}
}
我正在尝试在第一次迭代后打印元素,并希望查看使用代码编号解释 java 错误的列表。
您遇到的错误是由于
ArrayIndexOutOfBoundsException
造成的。发生此错误的原因是访问数组元素时循环中出现差一错误。 Java 数组是零索引的,这意味着大小为 N 的数组的有效索引是从 0 到 N-1。但是,在循环中,您从 1 迭代到 N+2,这超出了数组的范围。
要解决此问题,您应该将循环索引调整为从 0 开始,直到 N+1。这是更正后的代码:
import java.util.*;
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 = 0; i < N; i++) { // Start from 0, not 1
A[i] = sc.nextInt();
}
int X = sc.nextInt();
int Y = sc.nextInt();
// Insert element Y at position X by shifting elements to the right
for (int i = N + 1; i >= X; i--) {
A[i] = A[i - 1];
}
A[X] = Y;
// Print the updated array
for (int i = 0; i <= N + 1; i++) { // Change the upper bound to N+1
System.out.print(A[i] + " ");
}
}
}
主要变化:
通过这些更改,您的代码应该按预期工作,没有任何数组索引错误。