0

In Java, each number is associated with a character. For example:

int ch = 65;
System.out.print((char)(ch)); // output: A

Similarly,

System.out.print((char)(66)); // output: B

and so on

This is my code:

for (int line = 1; line <= 4; line++) {
    for (int ch = 65; ch <= line; ch++) {
        System.out.print((char)(ch));
    }
    System.out.println();
}

I was expecting this output:

A
BC
DEF
GHIJ

Instead, I got:





(yup, nothing!)

What am I doing wrong?

  • 7
    Look at the loop condition of your inner `for` loop - the loop will run _until_ `ch <= line` - do you see what might be the issue? – maloomeister May 03 '23 at 13:23
  • 1
    ch<=line is always false – WannaBe May 03 '23 at 13:23
  • You have condition that 4 should be less than line and then condition that this line should be higher than 65 – Feel free May 03 '23 at 13:24
  • This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). – David May 03 '23 at 13:26

2 Answers2

2

Actually your condition ch <= line is always false.

To fix it and get the expected result you can change the conditions and the loop limits:

int startingChar = 65;
for (int line = 0; line < 4; line++) {
    int ch;
    for (ch = startingChar ; ch <= startingChar + line; ch++) {
        System.out.print((char)(ch));
    }
    startingChar = ch;
    System.out.println();
}
Julien Sorin
  • 703
  • 2
  • 12
0

In the inner loop, ch starts at 65 and has to be smaller than or equal to line from the outer loop. But line from the outer loop goes from 1 to 4 - none of these four values is bigger than or equal to 65 (the smallest possible value for ch)

This is the reason why your inner loop is never entered.

You could try to do a "desk test" by writing down the values of your variables on a piece of paper and play that you are the computer and execute all the steps manually.

cyberbrain
  • 3,433
  • 1
  • 12
  • 22