如何将垂直列表输出到水平列表

How do I output the vertical list into horizontal lists

public class NormalNumbers {

  public static void main(String[] args) {

    int x = 1;

    while ((x >= 1) && (x <= 100)) {

      System.out.println("x = " + x);

      x = x + 1;

    }
  }
}

当前输出为:

x = 1
x = 2
...
x = 100

我想将格式更改为:

x=1 x=2 x=3 x=4 x=5
x=6 x=7 x=8 x=9 x=10

等等。

如何实现?

System.out.println prints the text and adds a new line. Use System.out.print 打印在同一行。

所以它会是这样的:

System.out.print("x=" + x + " ");

要每 5 个数字添加一个新行,请使用:

// if x is multiple of 5, add a new line
if (x % 5 == 0) {
    System.out.println();
}

PD:你可以使用x++increment operator)或x += 1(如果你想增加一个以上的单位)而不是x = x + 1

PD2:您可能希望使用制表 (\t) 而不是 space 来分隔数字。这样,两位数字的缩进与一位数字的缩进相同。

System.out.print("x=" + x + "\t");

不要使用 println(),它会自动在您正在打印的任何内容的末尾插入一个换行符,只需使用 print() 并添加一个额外的 space 来填充您的条目.

如果你想在 5 条目之后插入换行符,你可以使用空的 println() 和模数运算符,如下所示:

while ((x >= 1) && (x <= 100)) {
    System.out.print("x = " + x);
    if (x % 5 == 0) {
        System.out.println();
    }
    x = x + 1;
}

使用模数除法将您的计数器除以 5,如果没有余数,则创建一个新行:

int x = 1;

while ((x >= 1) && (x <= 100))
{
    System.out.print("x = " + x + " ");
    if(x % 5 == 0)
    {
        System.out.print("\n");
    }
    x = x + 1;

}
  • println 是下一行,print 在同一行。
  • x % 5 == 0 检查 x 值是否为 5 的倍数。

    int x = 1;
    
    while ((x >= 1) && (x <= 100)) {
    
        if (x % 5 == 0) {
            System.out.println("x="+x);
        } else {
            System.out.print("x=" +x+ " ");
    
        }
    
        x = x + 1;
    
    }
    

这给你输出

x=1 x=2 x=3 x=4 x=5
x=6 x=7 x=8 x=9 x=10
x=11 x=12 x=13 x=14 x=15
x=16 x=17 x=18 x=19 x=20
-----

我认为在你的情况下更好的方法是使用 for(;;) 语句:

for (int x = 1; x > 0 && x < 101;)
    System.out.print("x = " + x + (x++ % 5 == 0 ? "\n" : " "));

三元运算符x++ % 5 == 0 ? "\n" : " "负责换行和增加x变量。

输出:

x = 1 x = 2 x = 3 x = 4 x = 5
x = 6 x = 7 x = 8 x = 9 x = 10
...
x = 96 x = 97 x = 98 x = 99 x = 100