grammar
Switch (expression) { Case X: // code block BREAK ; Case Y: // code block BREAK ; default : // block }
switch
Statement works like this:
switch
The expression is evaluated once.- The value of the expression of each
case
comparison value. - If it matches, the code associated with the block is executed.
break
Anddefault
keyword is optional
Real case
package cn.test.logan.day05; import java.util.Scanner; public class ShopMenu { public static void main(String[] args) { System.out.println ( "Welcome to the Logan mall, select the action you want!" ); Scanner sc = new Scanner(System.in); boolean flag = true; while(flag) { System.out.println ( "1. browse merchandise; 2 shopping; 3. View Cart; 4. modify the cart; 5. submitted orders; 6. payment; 7 Exit" ); // user input String cmd = sc.nextLine (); switch(cmd) { case "1": System.out.println ( ". 1) eggplant 2.5 / kg \ n2) Maize 8 / kg \ n3) Orange 12 is / kg \ n-" ); BREAK ; Case "2" : System.out.println ( "are shopping ....." ); BREAK ; Case "3" : System.out.println ( "viewing shopping ....." ); BREAK ; Case "4" : System.out.println ( "being modified cart ....." ); BREAK ; Case "5" : System.out.println ( "is being submitted orders ....." ); BREAK ; Case "6" : System.out.println ( "Payment in ....." ); BREAK ; Case "7" : flag = false; break; default: System.out.println ( "select items you entered is not valid ...." ); } } } }