这是一种可以随意移动数字的方法。我冒昧地发表评论是为了让您更好地了解正在发生的事情。
public static void shift(int[] numbers) {
//Store the first element
int first = numbers[0];
//Start for-loop at the beginning of the array, stop before the last element
for (int i = 0; i < numbers.length - 1; i++)
//Take the number at the next index (i + 1) and store it in the current index (i)
numbers[i] = numbers[i + 1];
//Don't forget about the first number!
numbers[numbers.length - 1] = first;
}
下面的sn-p应该把数组的内容改成{0, 3, 4, 2, 4}
shift(new int[] {4, 0, 3, 4, 2})
这是一个完整的、可运行的类文件。
import java.util.Arrays;
public class Shift {
public static void main(String[] args) {
int[] numbers = new int[] {4, 0, 3, 4, 2};
shift(numbers);
System.out.println(Arrays.toString(numbers));
}
public static void shift(int[] numbers) {
//Store the first element
int first = numbers[0];
//Start for-loop at the beginning of the array, stop before the last element
for (int i = 0; i < numbers.length - 1; i++)
//Take the number at the next index (i + 1) and store it in the current index (i)
numbers[i] = numbers[i + 1];
//Don't forget about the first number!
numbers[numbers.length - 1] = first;
}
}
编辑:
要使用名为list 的ArrayList,可以使用以下sn-p:
list.add(list.remove(0));
这是因为ArrayList.remove(int) 将返回从数组中移除的对象,所以我们可以将其添加到末尾。