java中数组列表的arraylist移位元素
所以我试着将一个数组向右移动,这样x将显示为4,5,6,7,1,2,3。我认为我的算法是正确的,但出于某种原因,它不会返回x,只是跳过“x=rotate(x,3)”行之后的任何内容。任何帮助或解释都将不胜感激
public class Ex1sub3 {
public static void main(String[] args){
double[] x = {1, 2, 3, 4, 5, 6, 7};
System.out.println("Before rotation: ==============================");
for (int i = 0; i < x.length; i++)
{
System.out.println("x[" + i + "]: " + x[i]);
}
x = rotate(x, 3);
System.out.println("After rotation:==============================");
for (int i = 0; i < x.length; i++)
{
System.out.println("x[" + i + "]: " + x[i]);
}
}
private static double[] rotate(double[] x, int n){
int l = x.length;
double [] r = x;
int c = 0;
int rotation;
int startRotation = 0;
for (c = 0; c < l; c++)
{
rotation = c+n;
while (rotation < l-n)
{
x[c] = r[rotation];
}
if (rotation >= l-n)
{
x[c] = r[startRotation];
startRotation++;
}
}
return x;
}
}
# 1 楼答案
这是调试器可以帮助您查看的地方,但是,一个问题是您正在覆盖第一个要复制到的值,而不保留它。e、 g
假设你有两个元素,
{ 1, 2 }
你要做的第一件事是复制x[1] = x[0]
数组是{ 1, 1 }
,也就是说,你写了一个你无法得到的值。相反,您需要保留要复制的值。e、 g当您按
n
移位时,这会更复杂,但它是可以做到的。一个更简单的解决方案是在旋转之前复制阵列# 2 楼答案
您的程序不会跳过任何行,但会卡在
rotate(...)
函数中。我看不到离开内部while
循环的方法,因为条件中的所有变量在主体中都未被触及。但正如@Peter Lawrey已经提到的:在程序流神秘的情况下,调试器可能会被证明是有用的