英文:
Creating a Table of Numbers using Printf in Java
问题
我试图制作一个表格,以十进制格式打印从0到255的数字。输出应每行16个数字,使用printf和%5d格式。我写了一个代码,但不知道如何在每打印16个数字后换行。
for (int x = 0; x < 255; x++) {
System.out.printf("%5d", x);
if ((x + 1) % 16 == 0) {
System.out.println();
}
}
但它会在一行中输出,哈哈。
英文:
Im trying to make a table that prints numbers from 0 to 255 in decimal format. The print out should be 16 numbers per line using printf and %5d format. I made a code but idk how to make it enter after every 16 numbers.
for(int x = 0; x <255;x++) {
System.out.printf("%5d\n",x);
But it prints out in a line lol.
答案1
得分: 1
你可以添加一个简单的条件
for(int x = 0, y = 0; x < 255; x++, y++){
if(y == 16)
{
System.out.printf("\n");
y = 0;
}
System.out.printf("%5d", x);
}
所以这里发生的情况是,我添加了一个名为 y 的变量,它在每次增加时,当 y 等于 16 时,进入 if 条件。在这里我们打印一个新行,并且为了使程序在每打印 16 个数字时换行,我将 y 返回为 0。
英文:
you can add a simpel condition
for(int x = 0,y=0; x <255;x++,y++){
if(y==16)
{
System.out.printf("\n");
y=0;
}
System.out.printf("%5d",x);
}
so what's happening here is that i added y veriable that's increments, every time y is equal to 16 it's entering the if condition,there we printing a new line and to make it so every 16 numbers the program will print a new line im returning y to 0.
答案2
得分: 0
尝试添加 if 语句:
if (i % 17 == 0) {
System.out.Println("");
}
基本上,每当索引等于能被17整除的数时,它会换行。您可能想要去掉 "\n"
,因为它会在每次迭代时跳到下一行。
英文:
try to add if statement:
if (i % 17 == 0) {System.out.Println("");
basically, every time the index equals a number that is divided by 17, it goes to the next line. And you may want to get rid of "\n" since it skips to the next line in every iteration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论