75.2k views
1 vote
Write a program that prompts the user to enter a letter and displays its corresponding

number.


Enter a letter: A


The corresponding number is 2


Enter a letter: a


The corresponding number is 2


Enter a letter: +


+ is an invalid input

User ColWhi
by
6.3k points

1 Answer

2 votes

Answer:

The program to this question can be given as:

Program:

import java.util.*; //import package.

public class Main //define class

{

public static int convert_Number(char ch_Ar) //decalre function.

public static void main(String[] ar) //define main method

{

String Phone_Number,output = ""; //define variable

char ch;

int digit;

Scanner ob = new Scanner(System.in); //create Scanner class object for user input.

System.out.print("Enter a letter : "); //message

Phone_Number=ob.next(); //input from user

for(int i = 0 ; i <Phone_Number.length() ; i++)

{

ch = Character.toUpperCase(Phone_Number.charAt(i)); //input change into UpperCase

if(Character.isLetter(ch)) //conditional statement.

{

digit = convert_Number(ch); //calling function and hold value..

output = output + digit;

System.out.print("The corresponding number is: "+output); //print value.

}

else

{

output = output + ch;

System.out.print(output+" is an invalid input"); //message

}

}

}

}

Output:

Enter a letter : a

The corresponding number is: 2

Enter a letter : A

The corresponding number is: 2

Enter a letter : ++

+ is an invalid input

Step-by-step explanation:

In the above java program firstly we import the package for user input. Then we declare class i.e Main.In this class, we declare a function that is convert_Number. This function uses the if-else statement. In the if statement we use the OR (||)operator that is used to check multiple values in that operator if any of the conditions is true it returns a value. else return 0; Then we declare the main method in this method we declare the variable that is Phone_Number, output, ch_Ar, and digit. In that first two variables are string type and one is char and integer type. Then we create a scanner class object for user input and hold the value in the Phone_number variable. Then we declare loop and change the user input into the uppercase and hold the value into the ch_Ar variable and use the if-else statement. In if statement if the value matches then the digit variable the value of called function and it prints the value else condition not match then it will print its corresponding number that is invalid input.

User Nightking
by
6.5k points