如何将数组中的 5 个整数打印到一行

我编写了一个程序,它将加载 50 个范围在 0 到 128 之间的随机整数的数组。我试图打印该数组,每行只打印 5 个整数。但是,我似乎做不到。


public static void printList(int len, int[] list){

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

            System.out.println(list[i]);

        } // end for 

} // end printList

我希望每行输出只有 5 个整数。


PIPIONE
浏览 166回答 4
4回答

青春有我

这可能有效:public static void printList(int len, int[] list){&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < len; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (i % 5 ==0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(list[i] + "\t");&nbsp; &nbsp; &nbsp; &nbsp; } // end for&nbsp;} // end printList

红糖糍粑

重写@AmalK的代码:public static void printList(int len, int[] list) {&nbsp; &nbsp; for (int i = 0; i < len; i++) {&nbsp; &nbsp; &nbsp; &nbsp; String sep = "\t"; // usually have a tab after each integer&nbsp; &nbsp; &nbsp; &nbsp; if ((i+1) % 5 == 0 || i+1 == len)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; sep = "\n"; // but periodically use a newline instead&nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(list[i] + sep);&nbsp; &nbsp; }&nbsp;}我的改变是:每行5个数字;没有初始换行符;即使 len 不是 5 的倍数,最后一个数字后也换行;线上没有尾随制表符。

海绵宝宝撒

如果您确定数组的元素数量始终是 5 的倍数,则可以使用此方法。它为您节省了许多循环迭代。public static void printList(int len, int[] list){&nbsp; &nbsp; &nbsp; &nbsp; for (int i = 0; i < len; i+=5) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(list[i] + "\t"+ list[i+1] + "\t"+ list[i+1] +&nbsp;"\t"+ list[i+1] + "\t"+ list[i+1] + "\t");&nbsp; &nbsp; &nbsp; &nbsp; } // end for&nbsp;} // end printList

隔江千里

这应该工作正常:public static void printList(int len, int[] list) {&nbsp; &nbsp; for (int i = 0; i < list.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(list[i] + " , ");&nbsp; &nbsp; &nbsp; &nbsp; if (i % 5 == 0) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java