when i use recursive function it returns unexpected result

i've been trying to impelement rock,paper,scissor game in java. when i try to use getinput method : the first try returns right output 1 , 2 or 3(rock,paper,scissor declared static final in gamelogic class ..) but when i enter incorrect input then correct input it always returns 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;

}

1 answer

  • answered 2019-07-12 18:43 Nuthan Kumar

    try this

     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;
    
    }