Java条件语句失效:文本游戏移动系统异常求助
文本游戏移动系统问题修复方案
问题根源
- 状态未持久化:每次调用
movement()方法时,playerX、playerY和地图数组loclib都会重新初始化,玩家位置无法在多次指令间保存——这是east无法连续移动的核心原因,也是其他方向出错的主要诱因。 - 大小写敏感:北方向判断用的是
"North",与输入的指令大小写不匹配,导致无法识别。 - 初始位置重置:每次调用方法都把玩家位置重置为(0,0),导致south跳转至错误位置,west/north因初始位置不满足边界条件触发错误提示。
修复后的代码
import java.util.Scanner; public class Game { // 静态变量保存地图和玩家位置,确保状态持久化 private static String[][] loclib = { {"north pole", "geyser field", "hill"}, {"ridges", "ice spikes", "ridges"}, {"ice spikes", "plaines", "south pole"} }; private static int playerX = 0; private static int playerY = 0; public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.println("You wake up with a searing headache accomponied by a fizzing sound. After slowly standing up and"); System.out.println(" looking around you see your space ship infront of you. It is in pretty bad shape and it left a"); System.out.print("what will you do? "); boolean gameIsRunning = true; while (gameIsRunning) { String dir1 = input.next(); movement(dir1); } input.close(); } public static void movement(String in) { // 统一转小写,避免大小写敏感问题 String dir = in.toLowerCase(); if (dir.equals("west") && playerX > 0) { playerX--; System.out.println(loclib[playerY][playerX]); } else if (dir.equals("east") && playerX < 2) { playerX++; System.out.println(loclib[playerY][playerX]); System.out.println("Player position: x=" + playerX + ", y=" + playerY); } else if (dir.equals("south") && playerY < 2) { playerY++; System.out.println(loclib[playerY][playerX]); } else if (dir.equals("north") && playerY > 0) { playerY--; System.out.println(loclib[playerY][playerX]); } else { System.out.println("Either that word is not valid or you are trying to cross your restriction: " + dir); } } }
关键修改说明
- 静态变量存储状态:把地图和玩家位置设为类的静态变量,避免每次调用
movement()时重新初始化,确保位置在多次指令间保留。 - 统一指令大小写:用
toLowerCase()将输入转成小写,不管输入是North、NORTH还是north都能正确识别。 - 简化边界条件:调整方向判断的边界逻辑(比如
playerX < 2替代playerX>=0 && playerX<=1),让代码更简洁易懂。 - 规范类名:将类名
game改为Game,符合Java命名规范。
内容的提问来源于stack exchange,提问作者Iron_Lettuce
相关产品推荐
相关产品推荐

