Page 57 - CTS - CSA TP - Volume 2
P. 57
COMPUTER SOFTWARE APPLICATION - CITS
EXERCISE 86 : Use the switch statement
Objectives
At the end of this exercise you shall be able to
• know the syntax of switch statement and its use
• develop Java programs using switch statement.
Requirements
Tools/Materials
• PC/Laptop with Window OS
• JDK Software
• Text editor (Visual studio / Sublime / Note pad)
Procedure
A switch statement in Java provides an alternative way to express a multi-branch decision based on the value
of an expression. It’s often used when you have a single variable or expression whose value needs to be tested
against multiple conditions.
switch (expression) {
case value1:
// Code block executed if expression equals value1
break;
case value2:
// Code block executed if expression equals value2
break;
// Additional cases as needed
default:
// Code block executed if expression doesn’t match any case
break;
}
TASK 1: Select an option using a switch statement
import java.util.Scanner;
public class SimpleMenu {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println(“Select an option:”);
System.out.println(“1. Print Hello”);
System.out.println(“2. Print World”);
System.out.println(“3. Exit”);
int choice = scanner.nextInt();
switch (choice) {
case 1:
System.out.println(“Hello”);
42