gpt4 book ai didi

java - 复制数组的数组旋转时出现数组异常

转载 作者:行者123 更新时间:2023-12-01 20:17:58 25 4
gpt4 key购买 nike

我正在尝试对数组进行左旋转。但编译后我得到了

java.lang.ArrayIndexOutOfBoundsException

这是我的代码:

public class MyTest{

public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, k;
n = sc.nextInt();
k = sc.nextInt();
System.out.print(n+" "+k);
int inputArr[] = new int[n];
for(int i=0; i<n; i++){
inputArr[i] = sc.nextInt();
}

if(k > inputArr.length) {
k=k%inputArr.length;
}

int[] result = new int[inputArr.length];
System.arraycopy( inputArr, k+1, result, 0, k );
System.arraycopy( inputArr, 0, result, k, inputArr.length-1 );

itemPrint(inputArr);
itemPrint(result);
}

private static void itemPrint(int[] inputArr) {
for(int i=0; i<inputArr.length; i++){
System.out.print(inputArr[i]+" ");
}

}
}

这里是System.arraycopy( inputArr, k+1, result, 0, k );我收到错误。谁能解释一下我哪里做错了。

最佳答案

System.arraycopy( inputArr, k+1, result, 0, k );正在尝试复制索引 k+1 的元素直到k+k来自inputArr进入数组result .

如果您的inputArr (大小 n )有一个 length < k+k ,你自然会得到 ArrayIndexOutOfBoundsException

关于java - 复制数组的数组旋转时出现数组异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45436267/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com