我正在尝试使用方法将数组中的元素左移n(某些随机数)。难点在于将数组起始处的元素与末尾的元素交换。这是我的代码到目前为止。在n数组中循环移位元素n
其他阵列问题与此不同。
public class Shifty {
private int[] datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
public Shifty() {
datas = new int[]{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13};
}
public int shift(int position) {
int tmp = 0;
int[] tmp1 = new int[12];
for (int i = 0; i <= 12; i++) {
if (i < position) {
tmp1[12-position] = this.datas[i];
} else {
this.datas[i] = this.datas[i+1];
}
for (int j = 12-position; j <= 12; j++){
this.datas[j] = tmp1[j];
}
}
return position;
}
public void display() {
System.out.println(Arrays.toString(this.datas));
System.out.println();
}
}
例如看到这个:http://stackoverflow.com/questions/18659792/circular-arraylist-extending-arra- sylist和http://stackoverflow.com/questions/7266042/java-ring-buffer –
你的'tmp1'太小 - 应该是int [13],但int [datqs.length]会更稳健。在你的代码中使用'12'也是一样。 – Jan
哦,不好意思打错了。糟糕的手机键盘。 – Jan