gpt4 book ai didi

Java右移

转载 作者:行者123 更新时间:2023-12-01 11:48:00 24 4
gpt4 key购买 nike

所以我有一段代码将我的数组顺序移到右边。如何让它按照用户输入的次数移动?

  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;
}

最佳答案

尝试下面的代码:

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;
}

关于Java右移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29002248/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com