所以我试图将数组向右移动,以便 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, 2 }
你要做的第一件事是复制x[1] = x[0]
数组是{ 1, 1 }
即您重写了一个后面无法获得的值。相反,您需要保存要复制的值。例如
double d = x[1];
x[1] = x[0];
x[0] = d;
当你移动n
时,这会更复杂,但这是可以完成的。一个更简单的解决方案是在旋转之前获取数组的副本。
关于java - 在java中移动数组列表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33746644/