第六章第二十一题(电话按键盘)(Phone keypads) - 编程练习题答案
*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版)
上一篇: Linux Shell Map的用法详解
下一篇: shell 备份数据库、代码上线的脚本