How to use a nested While loops to display Rows and Columns in Java

Nicholas Zachariah :

I am trying to come up with the following output:

Row 1 Col A
Row 1 Col B
Row 2 Col A
Row 2 Col B

I am having trouble figuring out the logic to complete this task. So far I came up with the code provided below:

int iRowNum;
int iColLetter;

iRowNum = 1;
iColLetter = 65;

while (iColLetter < 67)
{

  System.out.println("Row " + iRowNum + " Col " + (char)iColLetter);

  iColLetter++;

  while (iRowNum < 3)
  {
    iRowNum += 1;
  }
}

Unfortunately, I receive the output of:

Row 1 Col A
Row 3 Col B

That begin said, I have a feeling I am getting close to where I need to be, but I spent a good chunk of time trying to figure out the logic behind my desired output.

Final Question How do I display the rows and columns as shown in the first block of this post?

Arvind Kumar Avinash :

Do it as follows:

public class Main {
    public static void main(String[] args) {
        int iRowNum = 1;
        int iColLetter = 65;
        while (iRowNum < 3) {
            iColLetter = 65;
            while (iColLetter < 67) {
                System.out.println("Row " + iRowNum + " Col " + (char) iColLetter);
                iColLetter++;
            }
            iRowNum += 1;
        }
    }
}

Output:

Row 1 Col A
Row 1 Col B
Row 2 Col A
Row 2 Col B

Explanation:

  1. Since you want the iRowNum to go up to 2, you start with while (iRowNum < 3) or while (iRowNum <= 2).
  2. For each value of iRowNum, the inner loop has to run for two times, starting with 65 i.e. you need to reset iColLetter to 65 before the start of the inner loop.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=216437&siteId=1