Search code examples
javareturn

Is it possible to return a value only if a certain thing happens, but not otherwise?


    public static String hero() {
       Scanner scanner = new Scanner(System.in);
       System.out.println("Which hero will you play as: Wizard, Elf or Dwarf?");
       heroType = scanner.nextLine();
       if (heroType.equalsIgnoreCase("wizard") || heroType.equalsIgnoreCase("elf") || heroType.equalsIgnoreCase("dwarf")){
           //code
           return heroType;
       }
       else {
           System.out.println("This character is not recognised, please choose from Wizard, Elf or Dwarf.");
           hero();
       }
   }

I want this method to return a heroType only if one of the 3 options is selected, otherwise it should call the method again. But this gives a compiler error as there is no return statement outside the if statement. The problem with having return statement at the end is that the main method has a "String h = hero();" and the "h" is passed to other methods, but if the user at first selects something other than wizard elf or dwarf, then corrects them selves, the "h" still stores the original incorrect value from the scanner the first time.

It should work as it is i think because the user will eventually have to give a correct value (as the method is just called again) and there will eventually be a return value, but it doesn't.


Solution

  • use :

    return hero(); 
    

    instead of just calling hero();