java - 如何摆脱 Java Nim 编程中的递归?

标签 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();
    } 

最佳答案

要消除递归,您需要

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

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

关于java - 如何摆脱 Java Nim 编程中的递归?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44677575/

相关文章:

java - 使用代理在 IBM MobileFirst Application Center Console 中上传外部应用程序时出现问题

Java String IndexOf 空字符串的行为

java - 为什么应用程序关闭并且 catch 子句没有捕获错误?

java - SSLSocket 客户端的输入流无法从服务器接收任何内容

Java调用类外的函数

Java Web Start - 更新一些用户?

java - 如何将自定义 getView 绑定(bind)到 ListView 适配器?

java - 为什么 Java 正则表达式在 Linux 和 Windows 上的行为不同?

java - 如何使用 Selenium WebDriver 进行拖放操作

java - PC 到设备的 Socket 连接失败