用Java中的Printf创建一个数字表格

huangapple go评论93阅读模式
英文:

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 &lt;255;x++) {
	     
	System.out.printf(&quot;%5d\n&quot;,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 &lt;255;x++,y++){
            if(y==16)
            {
                System.out.printf(&quot;\n&quot;);
                y=0;
            }   
            System.out.printf(&quot;%5d&quot;,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.

huangapple
  • 本文由 发表于 2020年9月9日 23:48:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/63815190.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定