我正在做一个Mancala游戏项目。如果您对GUI感兴趣,可以查看以下内容:
https://s32.postimg.org/hxzmhxt1x/mancala.png
我正在研究一种方法,它将使计算机玩家选择离他们商店最近的坑,这将允许它从人类玩家那里捕获石头。当最后一块石头落在正对着另一边有石头的坑对面的一个空坑里时,就会被捕获。我在下面包含了相关的方法。参数"theBoard“是一个整型数组,用来表示所有的坑,包括商店,以及数组的每个坑中包含多少块石头。下面是我为该方法编写的代码:
public int selectPit(int[] theBoard) {
int pitChoice = theBoard.length - 2;
while (pitChoice >= theBoard.length / 2) {
int destinationPit = theBoard[pitChoice] + pitChoice;
int opposite = (theBoard.length - 2) - destinationPit;
if (theBoard[destinationPit] == 0 && theBoard[opposite] > 0 && destinationPit <= (theBoard.length - 2) && destinationPit > (theBoard.length / 2)) {
return pitChoice;
} else {
pitChoice--;
}
}
return this.selectClosestPitWithStones(theBoard);
}最后一行调用selectClosestPitWithStones的代码是对backup方法的调用,以防没有允许捕获的选项。此备份方法的功能按预期工作。但是,我的selectPit方法总是返回错误的结果或"ArrayIndexOutOfBoundsException:-1“。
我正在使用正确编写的JUnit测试来测试此方法。这里有一个这样的测试:
@Test
public void testCapturePit0() {
this.setUp();
int[] theBoard = {6, 0, 0, 0, 2, 0, 0, 0};
assertEquals(4, this.strategy.selectPit(theBoard));
} 有什么可能导致不正确结果的想法吗?
发布于 2016-07-20 02:41:14
对其进行调试,并验证变量是否具有您期望的值。
目前的问题是其中一个变量超出了数组的界限。请记住,数组索引从0到长度减1。根据输入或数组的状态,int destinationPit = theBoard[pitChoice] + pitChoice;和int destinationPit = theBoard[pitChoice] + pitChoice;都可能越界。
https://stackoverflow.com/questions/38465879
复制相似问题