Page 194 - ComputerScience_Class_11
P. 194
For example,
1. //The following program snippet uses numeric data type
int choice=sc.nextInt();
switch(choice)
{
case 1: System.out.println("Good Morning"):
break;
case 2: System.out.println("Good Afternoon");
break;
case 3: System.out.println("Good Evening");
break;
default: System.out.println("Good Night");
}
Here, the variable choice is compared with the value of each case statement. Depending on the values 1 to 3, the
corresponding statement will be printed. If the value entered is other than 1 to 3, the message “Good Night” will
be displayed.
2. // The following program snippet uses character data type
int a=6, b=3;
char ch=sc.next().charAt(0);
switch(ch)
{
case '+' : System.out.println(" Sum : "+(a+b));
break;
case '-' : System.out.println(" Difference : "+(a-b));
break;
case '*' : System.out.println(" Product : "+(a*b));
break;
case '/' : System.out.println(" Quotient : "+(a/b));
break;
default: System.out.println("You have entered wrong choice");
}
Depending on the operator, the respective case is called. If “ch” does not match any case, default statement is
executed and the message “You have entered wrong choice” will be printed.
3. // The following program snippet uses String data type
import java.util.*;
class switchstring
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in);
int a=6, b=3;
String ch=sc.next();
switch(ch)
192 Touchpad Computer Science (Ver. 3.0)-XI

