所以我有一段代码将我的数组顺序向右移动一段。如何让它按用户输入的次数移动?
Scanner input = new Scanner(System.in);
int i;
int [] numberArray = {15, 14,13,12,11,10,9,8,7,6,5,4,3,2,1};
输出数组的代码。这里
System.out.println("\n");
System.out.println("How many positions do you want to shift?:");
input.nextInt();
public static void shiftRight(int[] list)
{
if (list.length < 2) return;
int last = list[list.length - 1];
for(int i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
答案 0 :(得分:1)
请尝试以下代码:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numberArray = { 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 };
randomArray(numberArray);
for (int i = 0; i < numberArray.length; i++)
System.out.print(numberArray[i] + " ");
System.out.println("\n");
System.out.println("How many positions do you want to shift?:");
int shiftTimes = input.nextInt();
input.close();
for (int i = 0; i < shiftTimes; ++i)
shiftRight(numberArray);
for (int j = 0; j < numberArray.length; j++)
System.out.print(numberArray[j] + " ");
}
public static void randomArray(int[] numberArray) {
Random rnd = new Random();
for (int i = 0; i < numberArray.length; i++) {
int randomPosition = rnd.nextInt(numberArray.length);
int a = numberArray[i];
numberArray[i] = numberArray[randomPosition];
numberArray[randomPosition] = a;
}
}
public static void shiftRight(int[] list) {
if (list.length < 2)
return;
int last = list[list.length - 1];
for (int i = list.length - 1; i > 0; i--) {
list[i] = list[i - 1];
}
list[0] = last;
}
答案 1 :(得分:0)
你做得对。现在只需循环调用方法:
改变
input.nextInt();
到
int shiftNumber=input.nextInt();
然后,
for(int i=0;i<shiftNumber;i++)
{
shiftRight(numberArray);
}