我对如何将 char 数组中的每个元素替换为数字有些困惑。
这是我目前的代码:
public static void main(String []args){
String[] dialTwo = {"a", "b", "c"};
String[] dialThree = {"d", "e", "f"};
String[] dialFour = {"g", "h", "i"};
String[] dialFive = {"j", "k", "l"};
String[] dialSix = {"m", "n", "o"};
String[] dialSeven = {"p", "q", "r", "s"};
String[] dialEight = {"t", "u", "v"};
String[] dialNine = {"w", "x", "y", "z"};
Scanner in = new Scanner(System.in);
System.out.print("Enter a phone number: ");
String phoneInput = in.next();
char[] inputToArray = phoneInput.toCharArray();
while (!phoneInput.matches("^[a-pA-P0-9]*$")) {
System.out.println("Not a valid number. Try agian.");
phoneInput = in.next();
}
如果有人想输入 ;;';';,我能够成功验证字符串。
谢谢大家的帮助。
我的老师也希望我使用方法类,但我对此有点困惑,所以我做了一些不同的事情。
所以我想要的输出,如果有人输入“CFG”,它会打印 123。
最佳答案
我的解决方案会更简单一些。
首先,我不会使用这些数组,而是使用一个二维数组,例如:
static char[][] keyboard = {
{'a','b','c'}, //2
{'d','e','f'}, //3
{'g','h','i'}, //4
{'j','k','l'}, //5
{'m','n','o'}, //6
{'p','q','r','s'}, //7
{'t','u','v'}, //8
{'w','x','y','z'} //9
};
然后,据此,我将循环处理您输入的每个字符。对于每个字符,我会搜索它是哪个数组。您需要的值是 index + 2
。因此,在 keyboard
上使用一个简单的 for 循环,您可以找到字符在哪里并打印您想要的值。当然,数字、空格和符号除外。
for each character in input
if character is numeric
output ( toNumeric ( character ) )
else
index = 0
while character not found
if character in array[index]
output ( index + 2 )
index++
对于更多的代码,嗯,你需要提供更多的信息,因为你也需要做一些工作;)
关于java - 如何将字符串中的字符转换为数字(转换为电话号码)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40987345/