1

I am trying to make a program that print the following numbers :

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4

The code is

   public class JavaApplication8 {

    public static void main(String[] args) {

        int i = 1;
        int j = 1;

        while (i <= 2 && j <= 4) {

            while (i <= 2 && j <= 4) {

                System.out.printf("%d%d\n", i, j);

                j++;
            }

            j = j - 4;

            i++;

            System.out.printf("%d%d\n", i, j);
            j++;

        }

    }
}

The program prints this

1 1
1 2
1 3
1 4
2 1
2 2
2 3
2 4
3 1

I don't know why this is happening behind the condition inside while says that it i must be smaller or equal 2

Smas
  • 33
  • 7

1 Answers1

2

It's outputting that final 3 1 because your final println statement (indicated below) is unconditional. So after incrementing i to 3, you still run that statement. The while condition only takes effect afterward, which is why it then stops after printing that.

public class JavaApplication8 {

    public static void main(String[] args) {

        int i = 1;
        int j = 1;

        while (i <= 2 && j <= 4) {

            while (i <= 2 && j <= 4) {

                System.out.printf("%d%d\n", i, j);

                j++;
            }

            j = j - 4;

            i++;

            System.out.printf("%d%d\n", i, j); // <=== This one
            j++;

        }

    }
}

That whole thing can be dramatically simpler, though:

public class JavaApplication8 {
    public static void main(String[] args) {
        for (int i = 1; i <= 2; ++i) {
            for (int j = 1; j <= 4; ++j) {
                System.out.printf("%d%d\n", i, j);
            }
        }
    }
}

Live Example

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • so, there is no way that it wont print 31 ? – Smas Nov 23 '16 at 17:25
  • 1
    @Smas: You just have to change your logic. I've shown one way you can change your logic above. Another would be to make that `println` conditional (guarded by an `if`), but with respect, that would be pretty non-optimal code, repeating that condition three separate places. – T.J. Crowder Nov 23 '16 at 17:28
  • Yes, It has worked for me with using if as you said. Thank you so much. – Smas Nov 23 '16 at 17:31