gpt4 book ai didi

Java:防止数组越界

转载 作者:行者123 更新时间:2023-12-01 16:06:41 24 4
gpt4 key购买 nike

我正在开发一款跳棋游戏,如果您想了解更多信息,可以在这里查看; http://minnie.tuhs.org/I2P/Assessment/assig2.html

当我进行测试以查看玩家是否能够从当前位置到达网格上的某个方 block (即 +1 +1、+1 -1 等)时,我得到一个 java.lang .ArrayIndexOutOfBoundsException 错误。

这是我用来进行移动的代码;

public static String makeMove(String move, int playerNumber)
{
// variables to contain the starting and destination coordinates, subtracting 1 to match array size
int colStart = move.charAt(1) - FIRSTCOLREF - 1;
int rowStart = move.charAt(0) - FIRSTROWREF - 1;
int colEnd = move.charAt(4) - FIRSTCOLREF - 1;
int rowEnd = move.charAt(3) - FIRSTROWREF - 1;


// variable to contain which player is which
char player, enemy;
if (playerNumber==1)
{
player= WHITEPIECE;
enemy= BLACKPIECE;
}
else
{
player= BLACKPIECE;
enemy= WHITEPIECE;
}

// check that the starting square contains a player piece
if (grid [ colStart ] [ rowStart ] == player)
{
// check that the player is making a diagonal move
if (grid [ colEnd ] [ rowEnd ] == grid [ (colStart++) ] [ (rowEnd++) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart--) ] [ (rowEnd++) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart++) ] [ (rowEnd--) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart--) ] [ (rowEnd--) ])
{
// check that the destination square is free
if (grid [ colEnd ] [ rowEnd ] == BLANK)
{
grid [ colStart ] [ rowStart ] = BLANK;
grid [ colEnd ] [ rowEnd ] = player;

}
}
// check if player is jumping over a piece
else if (grid [ colEnd ] [ rowEnd ] == grid [ (colStart+2) ] [ (rowEnd+2) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart-2) ] [ (rowEnd+2) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart+2) ] [ (rowEnd-2) ] &&
grid [ colEnd ] [ rowEnd ] == grid [ (colStart-2) ] [ (rowEnd-2) ])
{
// check that the piece in between contains an enemy
if ((grid [ (colStart++) ] [ (rowEnd++) ] == enemy ) &&
(grid [ (colStart--) ] [ (rowEnd++) ] == enemy ) &&
(grid [ (colStart++) ] [ (rowEnd--) ] == enemy ) &&
(grid [ (colStart--) ] [ (rowEnd--) ] == enemy ))
{
// check that the destination is free
if (grid [ colEnd ] [ rowEnd ] == BLANK)
{
grid [ colStart ] [ rowStart ] = BLANK;
grid [ colEnd ] [ rowEnd ] = player;
}

}
}

}

我不确定如何防止错误发生,您有什么建议?

最佳答案

首先想到的是在 if 语句条件中间使用后增量表达式,例如 (colstart++)。当然,在某些情况下这可能有用,但我不认为您的情况是其中之一。

使用(colstart+1)代替;它不会更改 colstart 变量本身的值,看起来这就是您真正想要做的。

更详细地说,假设 colstart 是 4:

System.out.println(colstart); // prints 4
System.out.println(colstart++); // prints 4
System.out.println(colstart); // prints 5

比较:

System.out.println(colstart); // prints 4
System.out.println(colstart+1); // prints 5
System.out.println(colstart); // prints 4

关于Java:防止数组越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2431146/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com