Pergunta

I want to make a menu that will make the program halt only when the user selects the exit option. I'd like to know your opinion about what's the best option and why.

switch statement:

do{
    menu();
    switch(option){
    case 1:
        method1();
        break;
    case 2:
        method2();
        break;
    }
} while(option != 3);
System.out.println("Bye!");
return;

or

Sequential if statements in a recursive method:

Scanner input = new Scanner(System.in);
int option = input.nextInt();
menu();
public void menu(){
    if(option == 1){
        method1();
    }
    if(option == 2){
        method2();
    }
    if(option == 3){
        System.out.println("Bye!");
        return;
    }
    menu();
}
Foi útil?

Solução

Your second approach won't even compile. You can not declare a function within a method in Java. Also either approach loops infinitely because you do not update option inside the loop.

Your first approach is better for various reasons.

  1. It is much easier to read.
  2. You should generally avoid recursion (its slower, uses more memory, usually harder to read).
  3. Using a switch statement has better performance than than a bunch of if-else's. Imagine you want the last option, a switch will branch directly to the correct case whereas an if-else will have to check every wrong condition on the way down.

Outras dicas

The switch statement is designed just for such scenarios as far as I know.
So I would use the first approach. The second approach is very exotic IMHO,
first time I see that kind of approach, and I am not sure if it's logically OK.

Okay, this is a beginners question, but:

 public enum MenuActions {
   ACTION1 , ACTION2, ACTION_EXIT
 }

...

switch(option) {
    case ACTION1:
       method1();

       break;
    ...
    case ACTION_EXIT;
        return;
}

Try to be declarative even when not using annotations. One look at the source should reveal what is going on to someone who has never seen it before.

And, taking up the point about recursion: Function / method call stacks have limited sizes. You should avoid recursive programming with undefined ( user defined) break-of-chain.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top