[英]Shift elements of array list in java
所以我試圖將數組向右移動,以使x出現為4、5、6、7、1、2、3。我認為我的算法是正確的,但是由於某種原因,它不會返回x並只是跳過“ x = rotation(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
時,這會更復雜,但是可以做到。 一個更簡單的解決方案是在旋轉之前獲取陣列的副本。
您的程序不會跳過任何行,但會停留在您的rotate(...)
函數中。 我看不到任何方法可以離開內部while
循環,因為條件中的所有變量在體內都沒有受到影響。 但是正如@Peter Lawrey已經提到的那樣:在程序流神秘的情況下,調試器可能會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.