Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.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 当我使用递归函数时,它会返回意外的结果_Java_Recursion_Return_Zero - Fatal编程技术网

Java 当我使用递归函数时,它会返回意外的结果

Java 当我使用递归函数时,它会返回意外的结果,java,recursion,return,zero,Java,Recursion,Return,Zero,我一直在努力推动java中的石头、纸、剪刀游戏。 当我尝试使用getinput方法时:第一次尝试返回正确的输出1、2或3(在gamelogic类中rock、paper、scissor声明为静态final…) 但当我输入不正确的输入,然后正确输入时,它总是返回0 public int getInput(){ System.out.println("Select ROCK , PAPER or SCISSOR"); String choice = scanner.nextLine

我一直在努力推动java中的石头、纸、剪刀游戏。 当我尝试使用getinput方法时:第一次尝试返回正确的输出1、2或3(在gamelogic类中rock、paper、scissor声明为静态final…) 但当我输入不正确的输入,然后正确输入时,它总是返回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;

}
试试这个

 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;

}

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