需要修复循环

问题描述 投票:0回答:1

我正在上在线课程,这使得获得帮助变得更加困难,这就是为什么我在这里。本周的讲座是关于嵌套循环的。他们把我弄糊涂了。我目前正陷在这个问题上。

给出numRows和numColumns,打印剧院中所有座位的列表。行编号,列字母编号,如1A或3E。在每个座位之后(包括最后一个座位之后)打印一个空格。使用单独的打印语句来打印行和列。例如:numRows = 2,numColumns = 3次打印:

1A 1B 1C 2A 2B 2C>

我尝试了许多可能的解决方案,这些解决方案产生了许多错误的结果。这是我目前的解决方案

    int numRows;
      int numColumns;
      int currentRow;
      int currentColumn;
      char currentColumnLetter;

      numRows = scnr.nextInt();
      numColumns = scnr.nextInt();

      currentColumnLetter = 'A'; 

         for (currentRow = 1; currentRow <= numRows; currentRow++)
         {

             for (currentColumn = 1; currentColumn < numColumns; currentColumn++)

             {
               System.out.print(currentRow);
               System.out.print(currentColumnLetter + " "); 

             }

              if( currentColumn == numColumns)
               {
                  currentColumnLetter++;
               }
         }

代码产生此结果

1A 1A 2B 2B 

期望的结果是

1A 1B 2A 2B

我已经做了两天了,这让我感到非常沮丧。预先感谢您的帮助。

java for-loop
1个回答
0
投票

您非常接近。

但是,您没有正确处理列名。每行开始时,您需要返回A,并在每一列中加一:

for (currentRow = 1; currentRow <= numRows; currentRow++) {
    currentColumnLetter = 'A'; //Starting a new row, reset the column to `A`
    for (currentColumn = 1; currentColumn < numColumns; currentColumn++){
        System.out.print(currentRow); 
        System.out.print(currentColumnLetter + " ");
        currentColumnLetter++;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.