Joe*_*ohn 5 java arrays rotation
我已经编写了一个程序来移动一个int数组,但找不到一种方法来移动它.如果您有任何关于如何根据空格数(int x)"旋转"我的数组的想法,你可以看看我的代码和评论,因为它目前只向左移动.谢谢
public void makeRight(int x) {
int[] anArray = {0, 1, 2, 3, 4, 5};
int counter = 0;
while (counter < x) {
int temp = anArray[0];
for (int i = 0; i < anArray.length - 1; i++) {
anArray[i] = anArray[i + 1];
}
anArray[anArray.length - 1] = temp;
counter++;
}
for (int i = 0; i < anArray.length; i++){
System.out.print(anArray[i] + " ");
}
}
Run Code Online (Sandbox Code Playgroud)
Jyo*_*aja -1
只需像这样更改代码即可
public void makeRight(int x) {
int[] anArray = {0, 1, 2, 3, 4, 5};
int counter = 0;
while(counter< x){
int temp = anArray[anArray.length - 1];
for (int i = anArray.length - 1; i > 0; i--) {
anArray[i] = anArray[i - 1];
}
anArray[0] = temp;
counter++;
}
for (int i = 0; i < anArray.length; i++)
System.out.print(anArray[i] + " ");
}
Run Code Online (Sandbox Code Playgroud)