Menu
Topics Index
...
`


Control Statements > Selection Statements >
Siva Nookala - 12 Apr 2016
About Nested Switch Statement In Java :
Similar to if statement, switch statements can be nested as well.

Print Subjects
class PrintSubjects
{
    public static void main(String arg[])
    {
        char branch = 'E'; // C - CSE, E - ECE, M - Mech
        int year = 2;
        
        switch( year )
        {
            case 1:
                System.out.println("English, Maths, Drawing");
                break;
            case 2:
                switch( branch ) // LINE C
                {
                    case 'C':
                        System.out.println("Data structures, Java, Computer Organization");
                        break;
                    case 'E':
                        System.out.println("Micro processors, Logic switching theory");
                        break;
                    case 'M':
                        System.out.println("Drawing, Manufacturing Machines");
                        break;
                }
                break;
            case 3:
                switch( branch ) // LINE D
                {
                    case 'C':
                        System.out.println("Operating System, RDBMS");
                        break;
                    case 'E':
                        System.out.println("Fundamentals of Logic Design, Microelectronics");
                        break;
                    case 'M':
                        System.out.println("Internal Combustion Engines, Mechanical Vibration");
                        break;
                }
                break;
        }
    
    }
}
OUTPUT

Micro processors, Logic switching theory

DESCRIPTION

This program prints the engineering subjects for a given branch and year. Variable branch specifies the branch - 'C' for CSE, 'E' for ECE, 'M' for Mechanical and the year specifies the year 1, 2, 3 or 4. We have used nested switch to print the subjects.
For first year since every branch has same subjects, there is no inner switch. But from second year there is an inner switch which prints, different subjects for different branches. We have intentionally not included the subjects for fourth year.

THINGS TO TRY
  • Add the case for final year (year 4) and print the subjects in the final year.
  • Support additional branch IT with branch code 'I'. This means we have to include the case statements for this branch (case 'I':) in switch block at LINE C for 2nd year and in switch block at LINE D for 3rd year.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.