Assignment: Module 03 - Part 01
Assignment: Module 03- Part 01
04. Write a class SwitchCaseExample to display the color using switch ..case.. Read the character from the user.
Input: R--> Red
G--> Green
B--> Blue
Select a letter
G
Output: your favorite color is green
import java.util.Scanner;
public class SwitchCaseExample {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Select a letter: R, G, B");
char letter = input.next().charAt(0);
switch (letter) {
case 'R':
System.out.println("Your favorite color is red");
break;
case 'G':
System.out.println("Your favorite color is green");
break;
case 'B':
System.out.println("Your favorite color is blue");
break;
default:
System.out.println("Invalid selection");
break;
}
}
}
This is an example of how you can use a switch case statement in Java to display the color based on the user's input. The program prompts the user to enter a letter (R, G, or B) and then uses a switch case statement to check the value of the input. Depending on the input, the program will display the corresponding color. If the input is not R, G, or B, it will display an "Invalid selection" message.