![](/img/trans.png)
[英]Is there a way to print out a varying number of elements from an array on each line
[英]Print an array elements with 10 elements on each line
我剛剛創建了一個包含 100 個初始化值的數組,我想在每一行打印出 10 個元素,所以它會是這樣的
0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26
這是我使用的代碼,我設法為前 10 個元素執行此操作,但我不知道如何為其余元素執行此操作
public static void main(String[] args) {
int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};
int i, count = 0;
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 9)
for (i = 9; i < numbers.length; i++)
System.out.println(numbers[i] + " ");
}
}
int[] numbers = new int[100];
for (int i = 0; i < numbers.length; i++) {
if (i % 10 == 0 && i > 0) {
System.out.println();
}
System.out.print(numbers[i] + " ");
}
這會在打印numbers[i]
之前打印一個換行符,其中i % 10 == 0
和i > 0
。 %
是 mod 運算符; 如果i / 10
則返回余數。 所以當i = 0, 10, 20, ...
時, i % 10 == 0
。
至於你的原始代碼,你可以做一些修改,如下所示:
int count = 0;
for (int i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10) {
System.out.println();
count = 0;
}
}
基本上, count
是您在這一行中打印了多少個數字。 一旦達到 10,您就打印換行符,然后將其重置回 0 ,因為您要開始一個新行,而對於該行,您還沒有打印任何數字(還)。
請注意,在上述兩種解決方案中,每行末尾都會打印一個額外的空格。 這是一個更靈活的實現,僅在必要時使用分隔符(水平和垂直)。 它只是稍微復雜一些。
static void print(int[] arr, int W, String hSep, String vSep) {
for (int i = 0; i < arr.length; i++) {
String sep =
(i % W != 0) ? hSep :
(i > 0) ? vSep :
"";
System.out.print(sep + arr[i]);
}
System.out.println(vSep);
}
如果你把它叫做print(new int[25], 5, ",", ".\\n");
,那么它將打印 25 個零,每行 5 個。 每行末尾有一個句點 ( .
),一行中的零之間有一個逗號 ( ,
)。
為什么要使用 2 個嵌套循環,只需記住在哪些位置需要輸出換行符? 同樣,對兩個循環使用相同的變量i
也不會達到您的預期。
怎么樣:
for (i = 0; i < numbers.length; i++) {
System.out.print(numbers[i] + " ");
count++;
if (count == 10)
System.out.print("\n");
count = 0;
}
}
您所要做的就是在每十個數字后打印出一個換行符。
for (i = 0; i < numbers.length; ++i)
{
System.out.print(number[i]);
if (i % 10 == 9)
{
System.out.println();
}
else
{
System.out.print(" ");
}
}
我知道這是一個老問題,但我只是想回答。 在 java 8 中,您可以在一行中完成此操作。 Arrays.stream(arr).forEach(s->System.out.print(s%10 > 0 ? s+" ":"\\n"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.