Java程序在一行中输出固定数量的数组元素
要在一行中输出固定数量的数组元素,我们应检查条件,如果条件成立,则应放置System.out.println();。正确地获得一条线,过程继续进行。
在这里,我们将在一行中显示5个元素。首先,创建一个新的整数数组并添加一些元素-
int[] list = new int[50];
for (int i = 0; i < list.length; i++) {
list[i] = (int)(i + 20);
}现在,声明一个新变量并将其初始化为0。在for循环中检查该变量,该循环一直循环到数组的长度。显示5个元素后设置新行-
int output = 0;
for (int i = 0; i < list.length; i++) {
if (output == 5) {
System.out.println();
output = 0;
}
System.out.print(list[i] + ", ");
output++;
}示例
public class Demo {
public static void main(String[] args) {
int[] list = new int[50];
for (int i = 0; i < list.length; i++) {
list[i] = (int) (i + 20);
}
int output = 0;
for (int i = 0; i < list.length; i++) {
if (output == 5) {
System.out.println();
output = 0;
}
System.out.print(list[i] + ", ");
output++;
}
}
}输出结果
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短