我需要帮助来组织Java数组。下面的代码沿直线打印出随机数。但是,我希望代码打印出其中四个数字,然后继续换行。至关重要,我希望代码在第一行上打印出四个随机数,然后在第二行上打印出另外四个随机数,依此类推。
import java.util.Arrays;
import java.util.Random;
public class SelectionSort{
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] array = new int[200];
Random rand = new Random();
// for acsending order
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(1000000) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
System.out.print("\n");
// for descending order
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i] + ", ");
}
}
答案 0 :(得分:2)
您需要为每4个数字打印\n
import java.util.Arrays;
import java.util.Random;
public class SelectionSort {
public static void main(String[] args) {
int[] array = new int[200];
Random rand = new Random();
// for acsending order
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(1000000) + 1;
}
Arrays.sort(array);
System.out.println(Arrays.toString(array));
System.out.print("\n");
// for descending order
for (int i = array.length - 1; i >= 0; i--) {
System.out.print(array[i] + ", ");
if (i % 4 == 0) {
// print \n for each 4 numbers.
System.out.println("\n");
}
}
}
}