In: Computer Science
Write Java program that asks a user to input a letter, converts the user input to uppercase if the user types the letter in lowercase, and based on the letter the user the user enters, display a message showing the number that matches the letter entered.
For letters A or B or C display 2
For letter D or E or F display 3
For letter G or H or I display 4
For letter J or K or L display 5
For letter M or N or O display 6
For letter P or Q or R or S display 7
For letter T or U or V display 8
For W or X or Y or Z display 9
Use a switch statement in this program
Sample input and output would be user entering a small letter a and the output being:
"The letter you entered was A"
"The number associated with the letter you entered is 2"
Another example of input and output would be the used entering a small m and the output being:
"The letter you entered was M"
The number associated with the letter you entered is 6"
The below code gives the result as oer the requirement given in the question.
The code has been well commented to understand the logic.
Code:
import java.util.*;
public class Main {
public static void main(String args[]) {
String letter;
System.out.println("Enter a letter: ");
Scanner sc = new Scanner(System.in); // craete a Scanner class object to take input from user
letter = sc.nextLine(); // store the input in the variable
System.out.println("The letter you entered was "+ letter.toUpperCase() ); // string.toUpperCase() to convert into upper case
switch(letter.toLowerCase() ){ // the switch statement to generate the number associated with the letter
case "a": // multiple condition same result type of case statement
case "b":
case "c":
System.out.println("The number associated with the letter you entered is 2" ); // print statement for each case to generate the associated number
break;
case "d":
case "e":
case "f":
System.out.println("The number associated with the letter you entered is 3" );
break;
case "g":
case "h":
case "i":
System.out.println("The number associated with the letter you entered is 4" );
break;
case "j":
case "k":
case "l":
System.out.println("The number associated with the letter you entered is 5" );
break;
case "m":
case "n":
case "o":
System.out.println("The number associated with the letter you entered is 6" );
break;
case "p":
case "q":
case "r":
case "s":
System.out.println("The number associated with the letter you entered is 7" );
break;
case "t":
case "u":
case "v":
System.out.println("The number associated with the letter you entered is 8" );
break;
case "w":
case "x":
case "y":
case "z":
System.out.println("The number associated with the letter you entered is 9" );
break;
}
}
}
Output Screenshot :