Write a program that takes a single phone digit. If the digit is a letter, the n
ID: 3641691 • Letter: W
Question
Write a program that takes a single phone digit. If the digit is a letter, the number corresponding to the letter is returned by reference and return 0 by value indicating it is a valid digit. Here are the letters associated with each digit.
0 5 J K L
1 6 M N O
2 A B C 7 P Q R S
3 D E F 8 T U V
4 G H I 9 W X Y Z
If the digit entered is not one of the valid digits or valid letters, return –1 by value indicating that you have an invalid digit.
Sample Output from the Program:
Enter a phone digit (Q to quit): 2
The digit you entered is 2.
Enter a phone digit (Q to quit): F
The digit you entered is 3.
Enter a phone digit (Q to quit): $
The digit you entered is invalid.
Enter a phone digit (Q to quit): -1
The digit you entered is invalid.
Enter a phone digit (Q to quit): Q
Good bye!
Processing Logic:
ToDigit( ) method
Convert the digit to upper case
Use a switch statement to determine if the digit is valid
and convert the letters to digits
If the digit is invalid, return -1.
If the digit is valid, return 0.
Explanation / Answer
using System;
namespace PhoneDigit
{
class Program
{
static void Main(string[] args)
{
char digit = '';
while (Char.ToUpper(digit) != 'Q')
{
Console.Write("Enter a phone digit (Q to quit): ");
digit = Console.ReadLine()[0];
if (Char.ToUpper(digit) != 'Q')
{
if (ToDigit(ref digit) != -1)
{
Console.WriteLine("The digit you entered is " + digit);
}
else
{
Console.WriteLine("The digit you entered is invalid.");
}
}
}
Console.WriteLine("Good bye!");
}
public static int ToDigit(ref char chr)
{
chr = Char.ToUpper(chr);
switch (chr)
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
return 0;
case 'A':
case 'B':
case 'C':
chr = '2';
return 0;
case 'D':
case 'E':
case 'F':
chr = '3';
return 0;
case 'G':
case 'H':
case 'I':
chr = '4';
return 0;
case 'J':
case 'K':
case 'L':
chr = '5';
return 0;
case 'M':
case 'N':
case 'O':
chr = '6';
return 0;
case 'P':
case 'Q':
case 'R':
case 'S':
chr = '7';
return 0;
case 'T':
case 'U':
case 'V':
chr = '8';
return 0;
case 'W':
case 'X':
case 'Y':
case 'Z':
chr = '9';
return 0;
default:
return -1;
}
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.