国际标准的字母/数字匹配图如编程练习题4.15所示,编写一个方法,返回给定大写字母的数字。
package pack2;
import java.util.Scanner;
public class PhoneKeyboard {
public static void main(String[] args) {
try(Scanner input = new Scanner(System.in);) {
System.out.print("Enter a letter: ");
System.out.println(number(input.next().charAt(0)));
}
}
//电话键盘
public static String number(char c) {
//创建字符串缓冲器对象
StringBuffer stringBuffer = new StringBuffer("The corresponding number is ");
char ch = Character.toLowerCase(c); //将字符转换为小写后赋值
if(ch < 'a' || ch > 'z') //判定字符是否合法
return c+" is an invalid input";
if('a' <= ch && ch <= 'c') stringBuffer.append(2);
else if(ch <= 'f') stringBuffer.append(3);
else if(ch <= 'i') stringBuffer.append(4);
else if(ch <= 'l') stringBuffer.append(5);
else if(ch <= 'o') stringBuffer.append(6);
else if(ch <= 's') stringBuffer.append(7);
else if(ch <= 'v') stringBuffer.append(8);
else if(ch <= 'z') stringBuffer.append(9);
return stringBuffer.toString();
}
}