You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java嵌套循环问题求助:PO箱标签生成代码错误排查

Java嵌套循环错误排查:PO箱标签生成问题

问题分析

你的代码核心错误在于行号与列字母的对应逻辑完全搞反,导致输出不符合要求。具体问题点如下:

  1. 行号错误:你在内层循环中用currentColumn作为标签的数字部分,但实际上每行的数字应该是固定的行号(第一行1,第二行2...),而非列数。
  2. 列字母错误:你在外层循环中用currentRow计算列字母,导致每行的所有标签字母都相同(第一行A,第二行B...),但实际上每列的字母应该按A、B、C顺序递增,和行号无关。

修正后的代码

import java.util.Scanner;

public class LoopPatterns {
   public static void main (String[] args) {
      Scanner scnr = new Scanner(System.in);
      int numRows;
      int numColumns;
      int currentRow;
      int currentColumn;
      char currentColumnLetter;
   
      numRows = scnr.nextInt();
      numColumns = scnr.nextInt();

      /* 修正后的代码 */
      for(currentRow = 0; currentRow < numRows; ++currentRow){
          // 当前行的数字:从1开始,所以是currentRow + 1
          int rowNumber = currentRow + 1;
          
          for(currentColumn = 1; currentColumn <= numColumns; ++currentColumn){
              // 当前列的字母:A对应第1列,所以用currentColumn - 1偏移
              currentColumnLetter = (char)('A' + (currentColumn - 1));
              // 输出行号+字母+空格
              System.out.print(rowNumber + "" + currentColumnLetter + " ");
          }
          // 每行结束换行
          System.out.println();     
      }

   }
}

逻辑解释

  • 外层循环:遍历每一行,currentRow从0到numRows-1,通过currentRow + 1得到当前行的实际编号(1、2...numRows)。
  • 内层循环:遍历当前行的每一列,currentColumn从1到numColumns,通过'A' + (currentColumn - 1)计算对应字母(1→A,2→B...)。
  • 输出逻辑:每行内依次拼接行号和列字母,末尾加空格;内层循环结束后换行,进入下一行的生成。

测试输入3 4时,输出会完全符合要求:

1A 1B 1C 1D 
2A 2B 2C 2D 
3A 3B 3C 3D 

内容的提问来源于stack exchange,提问作者Oliver Madge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.26 11:00:26