0

鉴于我有以下决赛:

private static final char CLIPPING_LOWER = 'c';
private static final char CLIPPING_UPPER = 'C';
private static final char RESET_LOWER = 'r';
private static final char RESET_UPPER = 'R';
private static final char LOAD_LOWER = 'l';
private static final char LOAD_UPPER = 'L';
private static final char QUIT_LOWER = 'q';
private static final char QUIT_UPPER = 'Q';

并考虑开关盒:

        public void keyPressed(KeyEvent e) 
        {
            char usersChoice = e.getKeyChar();      // get the user's choice 
            switch(usersChoice)
            {
            case LOAD_UPPER:
                {
                    userPressedLoad();
                    break;
                }
            case LOAD_LOWER:
                {
                    userPressedLoad();
                    break;
                }                   

            case RESET_LOWER:
                {
                    userPressedReset();
                    break;
                }

            case RESET_UPPER:
                {
                    userPressedReset();
                    break;
                }

            case CLIPPING_LOWER:
                {
                    userPressedClipping();
                    break;
                }

            case CLIPPING_UPPER:
                {
                    userPressedClipping();
                    break;
                }

            case QUIT_UPPER:
                {
                    userPressedQuit();
                    break;
                }

            case QUIT_LOWER:
                {
                    userPressedQuit();
                    break;
                }                   

            default: 
                break;

            }

        }

是否可以在一个块中(以及c和...等)编写一个案例,而不是为一个单独的案例和另一个案例编写一个案例?CrRcC

4

4 回答 4

3

将案例组合在一起的一种解决方案

case LOAD_UPPER:
case LOAD_LOWER:
    userPressedLoad();
    break;

另一种解决方案是将输入转换为大写并在 switch 语句中仅使用大写

char usersChoice = Character.toUpperCase(e.getKeyChar());

case LOAD_UPPER:
    userPressedLoad();
    break;
于 2013-04-10T13:23:33.153 回答
2
case CLIPPING_LOWER:
case CLIPPING_UPPER: {
                    userPressedClipping();
                    break;
                }
于 2013-04-10T13:21:57.913 回答
2

您可以使用 usersChoice 使用 Character.toLowerCase,这样您就不必处理“R”、“C”等。

http://docs.oracle.com/javase/6/docs/api/java/lang/Character.html#toLowerCase(char)

于 2013-04-10T13:24:19.343 回答
1

是的,例如:

case LOAD_UPPER: case LOAD_LOWER:
{
    userPressedLoad();
    break;
}
于 2013-04-10T13:23:45.577 回答