【发布时间】:2015-12-03 02:17:21
【问题描述】:
我认为我混淆了方法,无法正确获取实际方法。请帮忙,数组需要向右旋转,第一个数字将成为最后一个数字。我根据用户输入的大小生成一个随机数组。然后我打印该数组,然后进行旋转,然后打印新数组,最后一个数字在后,最后一个数字在前。
import java.util.Scanner;
import java.util.Random;
public class modOne {
public static final int MIN = 1;
public static final int MAX = 15;
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int arraySize = 0;
System.out.println("How many arrays to rotate right?");
int howMany = input.nextInt();
while(howMany <= 0) {
System.out.println("ERROR! Should be positive. REENTER: ");
howMany = input.nextInt();
}
while(howMany > 0) {
System.out.println("Enter array size: ");
arraySize = input.nextInt();
}
int[] a = new int[arraySize];
int[] b = new int[arraySize];
getRand(a, MIN, MAX);
System.out.println("The array before rotation: ");
printArray(a);
System.out.println("THe array after rotation: ");
transArray(a);
printArray(b);
System.out.println("Enter array size: ");
arraySize = input.nextInt();
}
public static void getRand (int[] list, int size, int low, int up) {
Random rand = new Random();
for(int r = 0; r < size; r++) {
list[r] = rand.nextInt(up - low + 1) + low;
}
}
public static void printArray(int[] list, int size) {
for (int r = 0; r < size; r++) {
System.out.printf("%5d", list[r]);
if(r % 6 == 5)
System.out.println();
}
System.out.println();
}
public static void transArray(int[] list, int size) {
for(int r = 0; r < size - 1; r++) {
list[r] = list[r-1];
}
}
}
【问题讨论】:
-
您需要什么? {1,2,3,4,5,6} 变成 {6,1,2,3,4,5} 还是 {6,5,4,3,2,1}?
-
@antonu17 我需要这个:旋转前的数组:8 15 2 10 11 15 1 3 旋转后的数组:3 8 15 2 10 11 15 1
-
向右旋转,最后一位成为第一位。
-
为什么要使用整个循环来改变一个元素的位置?
-
是的,就像你的第一个例子。