Need Help working with Nested For loop to display a block of text (Java)

155 Views Asked by At

I need to make a block of text that looks like this:

1 1 4

1 2 3

1 3 2

1 4 1

I have currently got this code:

for (int x = 1; x <= 4; x++) {
 for (int y = 4; y >= 1; y--) {
  System.out.println("1 " + x + " " + y);
 }
 System.out.println();
}

but it outputs the wrong thing, as

1 1 4

1 1 3

1 1 2

1 1 1

1 2 4

1 2 3

1 2 2

1 2 1

1 3 4

1 3 3

1 3 2

1 3 1

1 4 4

1 4 3

1 4 2

1 4 1

Can somebody help me? is it something with my loop syntax or something that has to do with the insides? Plus im new here, please dont be too harsh.

3

There are 3 best solutions below

2
Richard K Yu On BEST ANSWER

It is a little strange, but one way you can do this with a nested loop is to break out of the inner loop and to have the logic that zvxf has in the inner loop instead of as a variable:

for (int x = 1; x <= 4; x++) {
        for (int y = 5-x; y >= 1; y--) {
        System.out.println("1 " + x + " " + y);
        break;
        }
    System.out.println();
}

Output:

1 1 4

1 2 3

1 3 2

1 4 1
1
jluims On

Your loop logic is incorrect. You have two loops and each runs 4 times so in total, your loop runs 16 times which isn't what you want. You want something like this.

for (int x = 1; x <= 4; x++) {
    int y = 4 - x + 1;
    System.out.println("1 " + x + " " + y);
    System.out.println();
}
0
Log1cChan_CN On

Each loop will go on util the number reaches 4 or 1, maybe just write down the logic on the sketch paper first, my friend. :D