题目:九键输入法
import java.util.*;
public class test1 {
public static char[] two = {'A','B','C'};
public static char[] three = {'D','E','F'};
public static char[] four = {'G','H','I'};
public static char[] five = {'J','K','L'};
public static char[] six = {'M','N','O'};
public static char[] seven = {'P','Q','R','S'};
public static char[] eight = {'T','U','V'};
public static char[] nine = {'W','X','Y','Z'};
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("输入只包含1-9的数字串:");
String str = sc.next();//输入数字串
char[] chars = str.toCharArray();//将字符串转换为数组
StringBuilder result = new StringBuilder();//存放结果
for(int i = 0; i < chars.length ; ) {
boolean flag = false;//用来处理最后一个准备输出的字符:true:不输出 false:输出
int count = 1;//用来记录这个字符连着出现的次数
for (int j = i+1; j < chars.length; j++) {
if(chars[i] == chars[j]) {//若是连着输入字符,则统计该字符的数量
count++;
if (j == chars.length-1) {//处理连着输入相同的字符,且为最后一个待输出的字符
flag = true;
break;
}
continue;
}else {
break;
}
}
if (count == 1 && i == chars.length - 1){//处理最后一个待输出的字符,且不是连着输入的
flag = true;
}
if(count >= 1 && flag == false) {//处理输出的字符
if (chars[i] != '1') {//若为1,则不输出任何东西;否则,输出对应的字符
char[] value = getChar(chars[i]);
result.append(value[(count -1 )%value.length]);//添加结果
}
}
i = i + count;//i跳过之后count个字符
}
System.out.println(result.toString());
}
/**
* 获取对应的字符数组
* @param ch
* @return char[]
*/
public static char[] getChar(char ch) {
char c[] = new char[3];
switch (ch) {
case '1':
c = null;
break;
case '2':
c = two;
break;
case '3':
c = three;
break;
case '4':
c = four;
break;
case '5':
c = five;
break;
case '6':
c = six;
break;
case '7':
c = new char[4];
c = seven;
break;
case '8':
c = eight;
break;
case '9':
c = new char[4];
c = nine;
break;
}
return c;
}
}