所以我编写的代码将带一个字符并返回其字母数字键盘等效字符。问题是,我在框中得到一个问号作为回报。我检查过输入是否正确。例如,使用char'h'输入,我应该得到一个char'4'返回。希望有人能够发现我的错误。代码如下:
public char getDigit(char letter) throws Exception{
switch (letter) {
case 'a': case 'b': case 'c': case '2':
return 2;
case 'd': case 'e': case 'f': case '3':
return 3;
case 'g': case 'h': case 'i': case '4':
return 4;
case 'j': case 'k': case 'l': case '5':
return 5;
case 'm': case 'n': case 'o': case '6':
return 6;
case 'p': case 'q': case 'r': case 's': case '7':
return 7;
case 't': case 'u': case 'v': case '8':
return 8;
case 'w': case 'x': case 'y': case 'z': case '9':
return 9;
default:
throw new IllegalArgumentException("Must be a letter or number on the Alpha-Numeric Keypad.");
}
}
您的方法的返回类型是char。
现在拿你的switch语句。你返回的char值在2到9之间。现在看一下ASCII table。
惊喜:这些字符都是“不可打印”的控制字符。因此你的控制台给你“?”当你打印它们!
如果你想要'4',你的代码必须返回'4',而不是4!或者52,因为ASCII表中的条目表示'4'。
您没有获得正确的输出,因为您使用char
作为返回类型的getDigit(..)
函数。您应该使用int
作为返回类型而不是char
,因为在切换情况下,您要与字符进行比较并返回数字值。因此,使用以下代码替换您的代码,这将起作用:
public int getDigit(char letter) throws Exception{
switch (letter) {
case 'a': case 'b': case 'c': case '2':
return 2;
case 'd': case 'e': case 'f': case '3':
return 3;
case 'g': case 'h': case 'i': case '4':
return 4;
case 'j': case 'k': case 'l': case '5':
return 5;
case 'm': case 'n': case 'o': case '6':
return 6;
case 'p': case 'q': case 'r': case 's': case '7':
return 7;
case 't': case 'u': case 'v': case '8':
return 8;
case 'w': case 'x': case 'y': case 'z': case '9':
return 9;
default:
throw new IllegalArgumentException("Must be a letter or number on the Alpha-Numeric Keypad.");
}
}