Check Course and Subject
This program uses nested switch to print subject names based on course selection.
Problem Statement
Write a Java program that prints subject names based on course and subject code using nested switch.
Source Code
| 1 | public class CourseSubject { |
| 2 | public static void main(String[] args) { |
| 3 | int course = 1; |
| 4 | int subject = 2; |
| 5 | switch(course) { |
| 6 | case 1: |
| 7 | switch(subject) { |
| 8 | case 1: System.out.println("Course: CS, Subject: Java - Eduinq"); break; |
| 9 | case 2: System.out.println("Course: CS, Subject: Python - Eduinq"); break; |
| 10 | default: System.out.println("Invalid subject - Eduinq"); |
| 11 | } |
| 12 | break; |
| 13 | case 2: |
| 14 | switch(subject) { |
| 15 | case 1: System.out.println("Course: IT, Subject: Networking - Eduinq"); break; |
| 16 | case 2: System.out.println("Course: IT, Subject: Security - Eduinq"); break; |
| 17 | default: System.out.println("Invalid subject - Eduinq"); |
| 18 | } |
| 19 | break; |
| 20 | default: System.out.println("Invalid course - Eduinq"); |
| 21 | } |
| 22 | } |
| 23 | } |
Program Output
Course: CS, Subject: Python - Eduinq
Explanation
The program uses a switch on course. If course equals 1, another switch checks subject codes for CS subjects. If course equals 2, another switch checks IT subjects. Each nested switch ensures that subject selection is dependent on course selection. This demonstrates how nested switches can handle hierarchical decision-making, where one choice leads to another set of options. Shows how nested switch can manage multi-level decisions.