gpt4 book ai didi

Java:是否可以在for循环内换行x次?

转载 作者:行者123 更新时间:2023-11-29 10:02:55 29 4
gpt4 key购买 nike

我尝试通过 Google 和 StackOverflow 搜索我的问题,但没有找到任何答案。

我制作了一个数组,其中大小和值都是随机生成的。当数组值已打印 20 次时,我想换行,但不使用始终换行打印其余值。

这是我的代码:

public static void catArr() {

Random rändöm = new Random();
int size = rändöm.nextInt(100);

int[] arr = new int[size];

for (int i = 0; i < size; i++) {

arr[i] = rändöm.nextInt(100);
}

Arrays.sort(arr);

for (int i = 0; i < size; i++) {

System.out.print(" " + arr[i]);
if (i > 20)
System.out.println(); //How to do this only once?
else if (i > 40)
System.out.println(); //Same here?
}

}

这是生成的输出之一:

 3 8 10 25 30 31 34 38 46 50 55 59 62 66 67 68 68 68 72 76 76 81
82
83
84
86
91
92
93
94
94
97

我认为解决这个问题的一种方法是使用二维数组,但我想知道是否还有另一种方法。

感谢 Patric,我得到了想要的结果:

0   2   3   7   7   9   11  14  14  16  18  19  24  25  26  28  28  30  30  31  
31 33 33 34 41 41 41 42 43 44 45 46 51 51 52 53 59 60 61 62
62 62 63 65 65 67 67 68 69 70 74 74 76 78 82 83 84 84 87 88
89 93 93 94 94 94 95

最佳答案

尝试使用

if ( ( i % 20 ) == 0 ){
System.out.println();
}

如果我除以 20 没有余数,则打印一个新行!

关于Java:是否可以在for循环内换行x次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18205237/

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