我有方法来移动 arr 元素:
private static int[] shiftElements(int[] arr, int n) {
for (int i = 0; i < arr.length; i++) {
arr[i+n] = arr[i];
}
return arr;
}
n - amount of shifting.
当我执行此代码时,我遇到了一个异常:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 6
据我了解,程序需要更多空间来包含另一个项目。但我不需要添加更多项目,我需要已经存在的班次。使用n
参数,如果参数为负,则所有数组都向左移动,如果为正,则向右移动,如果为零 - 什么也不会发生。
Examples
ORIGINAL ARRAY: 1,3,5,6,8,10
example:
n = 2
arr: 8,10,1,3,5,6
How to achieve it?
您的例外来自这一行:
arr[i+n] = arr[i];
你得到一个例外,因为 i + n > arr.length。
从您的示例中,您希望将那些最终在数组之外的元素添加到前面。
我不会为你做作业,但你可能想为此使用if(...)
。或者mod
表达...
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句