使用 or 的 switch 语句

我正在创建一个控制台应用程序并使用 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.

我了解 switch 语句用于与常量进行比较,但是否可以执行以下操作?

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:
 }

关于该主题的更多信息: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

相关文章