所以我试图将一个数组向右移动,这样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;
}
}
答案 0 :(得分:1)
这是调试器可以帮助您查看的地方,但是,一个问题是您要覆盖您首先要复制的值而不保留它。 e.g。
假设你有两个元素,{ 1, 2 }
你要做的第一件事是复制x[1] = x[0]
数组是{ 1, 1 }
,即你写了一个你不能得到的值。相反,您需要保留要复制的值。例如
double d = x[1];
x[1] = x[0];
x[0] = d;
当您按n
换班时,这会更复杂,但可以这样做。一个更简单的解决方案是在旋转之前获取阵列的副本。
答案 1 :(得分:0)
您的程序不会跳过任何行,但会卡在rotate(...)
函数中。我看不出离开内部while
循环的方法,因为条件中的所有变量都是未触及的。但正如@Peter Lawrey已经提到的那样:在程序流程神秘的情况下,调试器可能会有用。