简体   繁体   中英

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;

    }
  }
}

The current output is:

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

I want to change the format to:

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

and so on.

How do I achieve that?

System.out.println prints the text and adds a new line. Use System.out.print to print on the same line instead.

So it would be something like this:

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

To add a new line each 5 numbers, use:

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

PD: You can use x++ ( increment operator ) or x += 1 (in the case you want to increase in more than one unit) instead of x = x + 1 .

PD2 : You might want to use a tabulation ( \\t ) instead of a space for separating your numbers. That way, numbers with two digits will have the same indentation than numbers with one digit.

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

Instead of using println() , which automatically inserts a newline character at the end of whatever you're printing, just use print() and add an extra space to pad your entries.

If you want to inject a newline after 5 entries specifically, you can do so with an empty println() and the modulus operator like so:

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

Divide your counter by 5 using modulus division if there is no remainder then create a new line:

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 is next line, print is on the same line.
  • x % 5 == 0 checks that the x values is a multiple of 5 or not.

     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; } 

That gives you output as

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
-----

I think that in your case the better way is using for(;;) statement:

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

The ternary operator x++ % 5 == 0 ? "\\n" : " " x++ % 5 == 0 ? "\\n" : " " is responsible for the new line and increment the x variable.

Output:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM