我在 Hacker Earth 上执行代码时收到以下错误:
[Execution failed.
Stack Trace:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at TestClass.Rotate(TestClass.java:25)
at TestClass.main(TestClass.java:62)](https://www.hackerearth.com/practice/codemonk/)
节目:
import java.util.*;
class TestClass {
// Function to rotate array
static void Rotate(int arr[], int d, int n) {
// Storing rotated version of array
int temp[] = new int[n];
// Keeping track of the current index
// of temp[]
int k = 0;
// Storing the n - d elements of
// array arr[] to the front of temp[]
for (int i = d+1; i < n-1; i++) {
temp[k] = arr[i];
k++;
}
// Storing the first d elements of array arr[]
// into temp
for (int i = 0; i < d+1; i++) {
temp[k] = arr[i];
k++;
}
// Copying the elements of temp[] in arr[]
// to get the final rotated array
for (int i = 0; i < n-1; i++) {
arr[i] = temp[i];
}
}
// Function to print elements of array
static void PrintTheArray(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
System.out.print(arr[i] + " ");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
// Taking input for array elements
for (int i = 0; i < n-1; i++) {
arr[i] = sc.nextInt();
}
int N = arr.length;
// Function calling
Rotate(arr, k, N);
// Printing the rotated array
PrintTheArray(arr, N);
}
}
如何修复此错误?
在访问阵列之前考虑添加调试指令。 您可以在使用索引 i 和 k 访问之前使用 System.out.println("i="+i") 和 System.out.println("k="+k") 。还打印数组长度以确保索引在范围内:System.out.println("size="+arr.length")。
问题出在这些行上: 临时[k] = arr[i]; k++;
在某个时刻,k 为 1,而临时大小为 1。此时 k 的最大值必须为 0。