【问题标题】:when i use recursive function it returns unexpected result当我使用递归函数时,它返回意外的结果
【发布时间】:2019-11-22 12:55:57
【问题描述】:

我一直试图在 Java 中实现摇滚、纸、剪刀游戏。 当我尝试使用 getinput 方法时:第一次尝试返回正确的输出 1、2 或 3(石头、纸、剪刀在游戏逻辑类中声明为静态最终 ..) 但是当我输入错误的输入然后正确的输入它总是返回 0 !

public int getInput(){

    System.out.println("Select ROCK , PAPER or SCISSOR");

    String choice = scanner.nextLine();

    choice = choice.toUpperCase();

    char c = choice.charAt(0);

    if(c == 'R'){
        return gameLogic.rock;
    }else if(c == 'P'){
        return gameLogic.paper;
    }else if(c == 'C'){
        return gameLogic.scissor;
    }
    getInput();
    return 0;

}

【问题讨论】:

  • 你为什么要使用递归呢?
  • 在用户输入正确的输入之前该方法不会退出
  • 也许你应该返回递归调用的值,即return getInput();,而不是丢弃它并返回一个固定的0。 --- 当然,在这种情况下,循环会比递归调用更好。

标签: java recursion return zero


【解决方案1】:

试试这个

 public static int getInput(){
    int result = 0;
    System.out.println("Select ROCK , PAPER or SCISSOR");
    Scanner scanner = new Scanner(System.in);
    String choice = scanner.nextLine();

    choice = choice.toUpperCase();

    char c = choice.charAt(0);
    if(c == 'R'){
        result = 1;
    }else if(c == 'P'){
        result = 2;
    }else if(c == 'C'){
        result = 3;
    } else {
         return getInput();
    }
    return result;

}

【讨论】:

    猜你喜欢
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-19
    • 1970-01-01
    • 1970-01-01
    • 2020-07-17
    相关资源
    最近更新 更多