switch语句中有多个字符? [英] Multiple characters in a switch statement?
问题描述
只是为了澄清这是硬件.
just to clarify this is hw.
在我们正在执行的项目中,不允许用户输入数字或特殊字符(即!@£等)
In a project we're doing, a user isn't allowed to enter numbers or special characters (i.e ! @ £ etc)
char letter;
String phonetic;
Scanner kb = new Scanner(System.in);
System.out.print("Please enter a letter: ");
letter = letter = kb.next().charAt(0);
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
case '1,2,3,4,5,6,7,8,9,0':
{
System.out.println('No number input please!');
}
break;
}
错误在
'1,2,3,4,5,6,7,8,9,0'
Eclipse说
invalid character constant
如果我必须手动输入所有数字,这真的很麻烦吗?
Isn't it really long winded if I have to enter all the numbers manually?
即情况'1':情况'2':
i.e. case '1': case '2':
即使
case 1,2,3,4,5,6,7,8,9,0:
这行不通.
是否有使用switch语句执行此操作的更短方法?
Is there an shorter way to do this using switch statements?
谢谢!
推荐答案
这是因为Case表达式应该是 java 7 中的int-compatible literal
或String
.
Its because Case expression should be an int-compatible literal
or a String
from java 7.
case '1,2,3,4,5,6,7,8,9,0':
字符文字用单引号表示. c
,它只能是一个长度,而您的情况不能反映这一点,因此是错误.
character literals are represented using single quotes. c
, it should only be of one length, while your case doesn't reflect that, thus the error.
'1,2,3,4,5,6,7,8,9,0' this is not a legal character.
如果您只是想检查字符是否仅是字母,请使用 Charcter#isLetter 在切换开始之前,如下面的代码所示:>
If you just wanna check if the character is only alpha, then use Charcter#isDigit(char) or Charcter#isLetter before the switch starts like in below code:
char ch= (Character.toUpperCase(letter);
if(!Character.isDigit(ch)) {
switch(Character.toUpperCase(letter))
{
case 'A':
{
Dot();
Dash();
Red();
}
break;
}
}
else {
System.out.println("no numbers please")
}
这篇关于switch语句中有多个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!