请帮我解决简单的java代码 - Code Monk

问题描述 投票:0回答:1

我在 Hacker Earth 上执行代码时收到以下错误

[执行失败。

堆栈跟踪: 线程“main”中的异常 java.lang.ArrayIndexOutOfBoundsException: 1 在 TestClass.Rotate(TestClass.java:25) 在 TestClass.main(TestClass.java:62)](https://www.hackerearth.com/practice/codemonk/)

Program: 

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);
    }
}

Please Help Me to Fixed This Error

java arrays indexoutofboundsexception
1个回答
0
投票

在访问阵列之前考虑添加调试指令。 您可以在使用索引 i 和 k 访问之前使用 System.out.println("i="+i") 和 System.out.println("k="+k") 。还打印数组长度以确保索引在范围内:System.out.println("size="+arr.length")

© www.soinside.com 2019 - 2024. All rights reserved.