*6.21(电话按键盘)国际标准的字母/数字匹配图如编程练习题4.15所示,编写一个方法,返回给定大写字母的数字,如下所示:
int getNumber(char uppercaseLetter)
编写一个测试程序,提示用户输入字符串形式的电话号码。输入的数字可能会包含字母。程序将字母(大写或者小写)翻译成一个数字,然后保持其他字符不变。
*6.21(Phone keypads)The international standard letter/number mapping for telephones is given in Programming Exercise 4.15. Write a method that returns a number, given an uppercase letter, as follows:
int getNumber(char uppercaseLetter)
Write a test program that prompts the user to enter a phone number as a string. The input number may contain letters. The program translates a letter (uppercase or lowercase) to a digit and leaves all other characters intact.
下面是参考答案代码:
// https://cn.fankuiba.com
import java.util.Scanner;
public class Ans6_21_page201 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter a string: ");
String phoneNumber = input.nextLine().toUpperCase();
for (int i =0; i < phoneNumber.length(); i++) {
if (Character.isDigit(phoneNumber.charAt(i))) {
System.out.print(phoneNumber.charAt(i));
}
else if (getNumber(phoneNumber.charAt(i)) == 1)
System.out.print("-");
else
System.out.print(getNumber(phoneNumber.charAt(i)));
}
}
public static int getNumber(char uppercaseLetter) {
int num = 99;
switch (uppercaseLetter+"") {
case "-":
num = 1;
break;
case "A":
num = 2;
break;
case "B":
num = 2;
break;
case "C":
num = 2;
break;
case "D":
num = 3;
break;
case "E":
num = 3;
break;
case "F":
num = 3;
break;
case "G":
num = 4;
break;
case "H":
num = 4;
break;
case "I":
num = 4;
break;
case "J":
num = 5;
break;
case "K":
num = 5;
break;
case "L":
num = 5;
break;
case "M":
num = 6;
break;
case "N":
num = 6;
break;
case "O":
num = 6;
break;
case "P":
num = 7;
break;
case "Q":
num = 7;
break;
case "R":
num = 7;
break;
case "S":
num = 7;
break;
case "T":
num = 8;
break;
case "U":
num = 8;
break;
case "V":
num = 8;
break;
case "W":
num = 9;
break;
case "X":
num = 9;
break;
case "Y":
num = 9;
break;
case "Z":
num = 9;
}
return num;
}
}
适用Java语言程序设计与数据结构(基础篇)(原书第11版)Java语言程序设计(基础篇)(原书第10/11版)更多内容
网友评论