使用或的switch语句 [英] Switch statement using or
问题描述
我正在创建一个控制台应用程序,并使用 switch
语句创建一个简单的菜单系统。用户输入采用单个字符的形式,在屏幕上以大写字母显示。但是,我确实希望程序接受大小写字符。
I'm creating a console app and using a switch
statement to create a simple menu system. User input is in the form of a single character that displays on-screen as a capital letter. However, I do want the program to accept both lower- and upper-case characters.
我知道开关
语句用于与常量进行比较,但是是否可以执行以下操作?
I understand that switch
statements are used to compare against constants, but is it possible to do something like the following?
switch(menuChoice) {
case ('q' || 'Q'):
//Some code
break;
case ('s' || 'S'):
//More code
break;
default:
break;
}
如果这不可能,是否有解决方法?我真的不想重复代码。
If this isn't possible, is there a workaround? I really don't want to repeat code.
推荐答案
这种方式:
switch(menuChoice) {
case 'q':
case 'Q':
//Some code
break;
case 's':
case 'S':
//More code
break;
default:
}
有关该主题的更多信息:
< a href = http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript> http://en.wikipedia.org/wiki/Switch_statement#C .2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript
More on that topic: http://en.wikipedia.org/wiki/Switch_statement#C.2C_C.2B.2B.2C_Java.2C_PHP.2C_ActionScript.2C_JavaScript
这篇关于使用或的switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!