Home > Mobile >  How to make a Java loop not print vertically
How to make a Java loop not print vertically

Time:11-19

I want to print a square using two half pyramids but it's displaying it vertically instead of printing out a square. I also encounter this problem in other patterns that I create using loops and I don't know how to resolve it. Here's my code:

for (int i = 1; i <= 5; i  ) {
    for (int j = 1; j <= i; j  ) {
        System.out.println("A");
    }
    for (int k = 5; k >= i; k--) {
        System.out.println("B");
    }
    System.out.println();
}

Expected result:

A B B B B B

A A B B B B

A A A B B B

A A A A B B

A A A A A B

CodePudding user response:

Use print instead of println.

for (int i = 1; i <= 5; i  ) {
    for (int j = 1; j <= i; j  ) {
        System.out.print("A");
    }
    for (int k = 5; k >= i; k--) {
        System.out.print("B");
    }
    System.out.println();
}

CodePudding user response:

all you have to do is replace the println with print

system.out.println("A"); 

the above code would print the text and then shift the curser to the next line

system.out.print("B");

this should do the thing

  • Related