Page 197 - ComputerScience_Class_11
P. 197

Nested switch case
                 When a switch case is used inside another switch case, then it is known as a nested switch case.

                 For example,
                                 Write a Java program that uses a nested 'switch' statement. The program should prompt
                  Program 3
                                 the user to enter an integer ('ch1') and a character ('ch2'). Based on the integer input, the
                                 program should evaluate a nested 'switch' for the character input.
                                 •   If the integer is '1', the inner 'switch' should check if the character is 'B', 'C' or 'D' and print
                                   the corresponding message.
                                 •  If the integer is '2', the program should print "The choice is 2".
                                 •  If the integer is '3', the program should print "The choice is 3".
                                 •  If the input doesn't match any of the cases, print "Wrong choice".
                   1      import java.util.*;
                   2      class nestedswitch

                   3      {
                   4          public static void main(String[] args)

                   5          {
                   6              Scanner sc = new Scanner(System.in);
                   7              int ch1;
                   8              char ch2;

                   9              System.out.println("Enter number ch1 and character ch2");
                  10              ch1 = sc.nextInt();

                  11              ch2 = sc.next().charAt(0);
                  12              // Starting of Outer Switch
                  13              switch(ch1)
                  14              {

                  15                  case 1:
                  16                      // Starting of Inner Switch

                  17                      switch (ch2)
                  18                      {
                  19                          case 'B': System.out.println("The choice is B");
                  20                              break;

                  21                          case 'C':
                  22                              System.out.println("The choice is C");

                  23                              break;
                  24                          case 'D':
                  25                              System.out.println("The choice is D");
                  26                              break;

                  27                      }





                                                                                              Statements and Scope  195
   192   193   194   195   196   197   198   199   200   201   202