如何在Java中使用我的Nim程序摆脱递归?

时间:2017-06-21 13:29:12

标签: java

我正在制作Nim游戏,我知道我已经在某处经历过递归,但我不确定如何修复它。有人可以帮我一把吗? 下面是您需要的代码,但如果需要,我可以获得更多。

提前致谢。

public static void changeDisplay() {
    //checks if the group picked equals one of the existing groups.
    if(groupPick.contentEquals("A") || groupPick.contentEquals("a")) {
        //checks if the group is equal to 0, avoids cheating.
        if(a == 0) {
            System.out.println("Nice try " + playerName + ", you can't take something from nothing.");
            gamePlaying();
        } else {
            //checks if the number picked is greater than the amount of elements in the group selected.
            while(numPick > a) {
                System.out.print("Error, you cannot take more than what is there. Please pick again: ");
                numPick = new Scanner(System.in).nextInt();
            }

        }

跳过了一些if语句。

} else {
        //runs this code if the group the player selected isn't a pre-existing group.
        System.out.println("Oops! "+ groupPick + " doesn't seem to be a group, please select a group (A, B, or C).");
        System.out.print(playerName + ", choose a pile: ");
        groupPick = new Scanner(System.in).nextLine();
        changeDisplay();
    }
        playerPicker++;
        display();
    } 

1 个答案:

答案 0 :(得分:1)

要删除递归,您需要

A)更改changeDisplay以返回一个bool,指示它是否仍然是脏的(需要再次调用)

B)将changeDisplay函数的内容包装在while(true) {...}中以重复该过程,使用return / break在完成后停止。