1 Write a switch statement to print out a string depending o
1. Write a switch statement to print out a string depending on the value of a char variable called ch.
If ch is:
\'a\' print \"excellent\"
ch is \'b\' print \"good\"
ch is \'c\' print \"ok\"
if ch is anything else, print \"invalid\"
Assume that ch has been properly declared and contains a value.
Solution
It prints out a string depending on the value of char variable ch.Taking the input from keyboard.If we enter \'a\' it prints excellent or \' b\' it prints good or \' c\' it prints ok..if anything else it prints \' invalid\'.
import java.util.Scanner;
public class SwitchCaseExample
{
public static void main(String[] args)
{
char ch=0;
Scanner s = new Scanner(System.in);
System.out.println(\"Enter Your Character:\");
ch=s.next().charAt(0);
switch (ch) {
case \'a\' :
System.out.println(\"Excellent!\");
break;
case \'b\' :
System.out.println(\"Good\");
break;
case \'c\' :
System.out.println(\"OK\");
break;
default :
System.out.println(\"Invalid\");
}
}
}
