我对编程还很陌生,并决定接受一个项目,在其中我在控制台中创建一个游戏。用户可以选择从 3x3 网格区域的中心向上、向下、向左或向右移动。x,y 位置之一被标记为“坏”方块,当用户的 x 和 y 等于坏方块的 x 和 y 时,游戏结束。坏方块的位置是x = 1和y = 3。我遇到的问题是,当用户输入 Up 或 Left(因此用户 y 变为 3 或用户 x 变为 1)并且游戏结束时,即使其他轴值之一与坏方块不匹配。这是我的代码:public static void main (String[]args){ //scanner Scanner userIn = new Scanner(System.in); //string that will get users value String movement; //strings that are compared to users to determine direction String up = "Up"; String down = "Down"; String left = "Left"; String right = "Right"; //starting coordinates of user int x = 2; int y = 2; //coordinates of bad square int badx = 1; int bady = 3; //message telling user options to move (not very specific yet) System.out.println("Up, Down, Left, Right"); //do while loop that continues until do { movement = userIn.nextLine(); //checking user input and moving them accordingly if (movement.equals(up)) { y++; } else if (movement.equals(down)) { y--; } else if (movement.equals(left)) { x--; } else if (movement.equals(right)) { x++; } else { System.out.println("Unacceptable value"); } //checking if user is out of bounds, if user tries to leave area, x or y is increased or decreased accordingly if (x < 0 || y < 0 || x > 3 || y > 3) { System.out.println("Out of bounds"); if (x < 0) { x++; } else if (y < 0) { y++; } else if (x > 3) { x--; } else if (y > 3) { y--; } } //message showing user x and y coordinates System.out.println("x =" + x + " y =" + y); } while (y != bady && x != badx); //what checks to see if user has come across the bad square //ending message (game ends) System.out.println("Bad Square. Game over.");}
3 回答
弑天下
TA贡献1818条经验 获得超8个赞
您的while(y != bady && x != badx)
测试测试y
还不错,x
也不错,因此只需其中之一即可false
让您的循环停止。
一个简单的解决方法可能是稍微交换您的逻辑。
while(!(y == bady && x == badx))
摇曳的蔷薇
TA贡献1793条经验 获得超6个赞
如果您考虑一下您的条件语句是如何表述的,while(y != bady && x != badx)
您会发现当x = 1
或 时y = 3
,AND 语句中的一侧评估为假并导致整个条件为假。你可以通过写来处理它:
while(y != bady || x != badx)
添加回答
举报
0/150
提交
取消