简体   繁体   中英

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.

use :

return hero(); 

instead of just calling hero();

I don't like recursive methods. Keep it simple and scalable.

public class Test
{
   private static final Set<String> HEROES = new HashSet<>(4);

   static {
      HEROES.add("wizard");
      HEROES.add("elf");
      HEROES.add("dwarf");
   }

   public static final void main(final String... args) {
      hero();
   }

   public static final String hero() {
      final Scanner scanner = new Scanner(System.in);
      String heroType;

      while (true) {
         System.out.println("Which hero will you play as: Wizard, Elf or Dwarf?");
         heroType = scanner.nextLine().trim().toLowerCase();

         if (HEROES.contains(heroType)) {
            return heroType;
         }

         System.out.println("This character is not recognised, please choose from Wizard, Elf or Dwarf.");
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM