如何修正Java二维数组中行优先移动换行的moveObject方法?
修正Java二维数组中对象移动的moveObject方法
我在一个小型Java应用中维护一个SIZE×SIZE的二维char数组FIELD,需要实现两个字符对象的移动逻辑,但Field类中的moveObject方法运行异常,移动后对象会跳到随机位置。需求如下:
- 将指定对象移动指定步数,支持行自动换行:当对象到达某行的SIZE-1索引位置时,下移到下一行并从0索引处继续移动
- 当对象到达右下角(索引为(SIZE-1, SIZE-1))位置时,停止移动
当前moveObject方法代码:
public void moveObject(Obj obj, int spaces) { // Get the current position of the object int oldRow = obj.getRow(); int oldCol = obj.getCol(); // Clear the current position of the player on the board field[oldRow][oldCol] = ' '; // Calculate the total number of spaces moved int totalSpaces = oldRow * SIZE + oldCol + spaces; // Calculate the new position of the object int newRow = (totalSpaces / SIZE) % SIZE; int newCol = totalSpaces % SIZE; // Update the object's position player.row = newRow; player.col = newCol; // Get the piece of the object char symbol = object.getSymbol(); // Set the new position of the object on the field field[newRow][newCol] = symbol; }
问题分析
- 变量引用错误:方法参数为
obj,但代码中错误使用了player、object等未定义或不相关的变量,导致对象位置更新和符号获取错误 - 未处理边界停止逻辑:没有判断是否到达右下角,会继续移动导致位置超出预期
- 总步数未做上限限制:当总步数超过数组总格子数(SIZE*SIZE)时,会出现循环移动,不符合需求
修正后的代码
public void moveObject(Obj obj, int spaces) { // 获取对象当前位置 int oldRow = obj.getRow(); int oldCol = obj.getCol(); // 若已在右下角,直接返回不移动 if (oldRow == SIZE - 1 && oldCol == SIZE - 1) { return; } // 清除原位置的字符 field[oldRow][oldCol] = ' '; // 计算当前位置对应的线性索引 int currentLinearIndex = oldRow * SIZE + oldCol; // 计算目标线性索引,最大不超过总格子数-1(即右下角的线性索引) int targetLinearIndex = Math.min(currentLinearIndex + spaces, SIZE * SIZE - 1); // 转换为二维数组索引 int newRow = targetLinearIndex / SIZE; int newCol = targetLinearIndex % SIZE; // 更新对象的位置(假设Obj类有对应的setter,若无则直接修改成员变量,需保证访问权限) obj.setRow(newRow); obj.setCol(newCol); // 获取对象符号并设置到新位置 char symbol = obj.getSymbol(); field[newRow][newCol] = symbol; }
修正说明
- 新增右下角判断:对象已在终点时直接返回,不再执行移动逻辑
- 统一变量引用:全程使用方法参数
obj,避免变量混淆 - 限制目标索引上限:用
Math.min确保目标位置不会超过右下角,避免循环移动 - 规范位置更新:使用对象的setter方法更新位置,保证代码封装性
内容的提问来源于stack exchange,提问作者user20028948
相关产品推荐
相关产品推荐

