题目如下: 手机的九宫格输入法中,输入数字的键位是可以和字母键位对应的。如“2”对应“ABC”,“9”对应“WXYZ”,现假设“1”和“0”为空字符,以此规则试设计一个程序,将单词用一串数字来进行表示。 举例: 输入:cat(不区分大小写) 输出:228
因为“1”和“0”表示空字符,所以不需要考虑。(如果是空字符也没办法表示,输出“0”或“1”不准确。假设需要考虑可以自己改写,很简单。) 按照流程,先是要输入一串字母,然后要把其中的小写变成大写,再用if,else if 进行判断即可。 这样这道题很快就能打完代码,但是还要考虑很多其他方面的问题,我为了省事,直接抛了异常。
import java.util.Scanner; public class Reform { public static void main(String[] args)throws Exception { // TODO Auto-generated method stub Scanner s=new Scanner(System.in); String str=s.nextLine(); s.close(); //判断输入字符的长度 int n=str.length(); //开始循环 for(int i=0; i<n; i++) { //将字符串字符一个一个取出 char c=str.charAt(i); //判断是否是小写并将之转换 if(c>='a'&&c<='z') { c-=32; } //判断字母输出数字 if(c>='A'&&c<='C'){ System.out.print(2); }else if(c>='D'&&c<='F'){ System.out.print(3); }else if(c>='G'&&c<='I'){ System.out.print(4); }else if(c>='J'&&c<='L'){ System.out.print(5); }else if(c>='M'&&c<='O'){ System.out.print(6); }else if(c>='P'&&c<='S'){ System.out.print(7); }else if(c>='T'&&c<='V'){ System.out.print(8); }else if(c>='W'&&c<='Z'){ System.out.print(9); }else { break; } } } }