gpt4 book ai didi

java - 如何将数组排序为列

转载 作者:行者123 更新时间:2023-12-02 02:03:39 24 4
gpt4 key购买 nike

我需要帮助在 java 中组织数组。下面的代码以直线打印出随机数。但是,我希望代码打印出其中四个数字,然后继续换行。重要的是,我希望代码在第一行打印出四个随机数,然后在第二行打印出另外 4 个随机数,依此类推。

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] + ", ");
}

}

最佳答案

您需要为每 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");
}
}
}
}

关于java - 如何将数组排序为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51182922/

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