Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/eclipse/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java中的Mancala游戏-在while循环中使用int数组_Java_Arrays_Junit_While Loop - Fatal编程技术网

Java中的Mancala游戏-在while循环中使用int数组

Java中的Mancala游戏-在while循环中使用int数组,java,arrays,junit,while-loop,Java,Arrays,Junit,While Loop,我正在做一个曼卡拉游戏项目。如果您对GUI感兴趣,请参阅: 我正在研究一种方法,可以让电脑玩家选择离他们商店最近的坑,这样就可以从人类玩家那里捕获石头。当最后一块石头落在一个空坑中,正好与另一侧有石头的坑相对时,就进行了捕获。我将在下面介绍相关的方法。参数“theBoard”是一个整数数组,用于表示所有坑,包括存储以及数组中每个坑中包含的石头数量。以下是我的方法代码: public int selectPit(int[] theBoard) { int pitChoice =

我正在做一个曼卡拉游戏项目。如果您对GUI感兴趣,请参阅:

我正在研究一种方法,可以让电脑玩家选择离他们商店最近的坑,这样就可以从人类玩家那里捕获石头。当最后一块石头落在一个空坑中,正好与另一侧有石头的坑相对时,就进行了捕获。我将在下面介绍相关的方法。参数“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);
    }

关于什么可能导致不正确的结果有什么想法吗?

调试它并验证变量是否具有您期望的值


目前的问题是其中一个变量超出了数组的边界。请记住,数组索引从0到长度减1。两个
int destinationPit=theBoard[pitChoice]+pitChoice
int destinationPit=theBoard[pitChoice]+pitChoice可能会超出范围,具体取决于输入或数组的状态。

是什么导致了不正确的结果?逻辑错误。使用调试器或输出一些调试System.out.println()语句。这是编程的一部分。您正在超出while循环中数组的边界。您必须调试它的迭代以发现原因。基于所涉及的值,发生这种错误是完全可行的。仔细考虑您的算法,编写更小的代码行,根据需要将值输出到System.out,直到达到您要求的方式为止。并对其进行彻底测试。
@Test
    public void testCapturePit0() {
        this.setUp();
        int[] theBoard = {6, 0, 0, 0, 2, 0, 0, 0};
        assertEquals(4, this.strategy.selectPit(theBoard));
    }