java - the best option to build one menu, switch-case or if-if-if? -


I want to create a menu that will close the program only when the user chooses to exit option. I want to know your opinion about this option and why.

Switch Statement:

  do {menu (); Switch (Option) {Case 1: Method 1 (); break; Case 2: Method 2 (); break; }} While (option! = 3); Println ("Bye!"); Return;   

or

sequential if details in a recursive method:

  scanner input = new scanner ( System.in); Int option = input.nextInt (); Menu (); Public Zero Menu () {if (option == 1) {method1 (); } If (option == 2) {method2 (); } If (option == 3) {System.out.println ("bye!"); Return; } Menu (); }    

Your second method will not even compile. You can not declare a function within a method in Java. Besides, you can infinitely detect loops because you do not update the options inside the loop.

Your first method is better than for various reasons.

  1. It is very easy to read.
  2. You should generally avoid using recycling (its slow, uses more memory, usually difficult to read).
  3. Use the switch statement if you have a better performance than a group of fifties Imagine that you want the last option, a switch will branch directly into the right case, while checking each other in the wrong position on each other. Have to do

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -