切换一组输入的情况?

时间:2013-04-10 13:19:48

标签: java switch-statement

鉴于我有以下决赛:

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;

            }

        }

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

4 个答案:

答案 0 :(得分:3)

将案件分组在一起的一种解决方案

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

另一个解决方案是convert the input to uppercase并且在switch语句中只使用大写

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

case LOAD_UPPER:
    userPressedLoad();
    break;

答案 1 :(得分:2)

case CLIPPING_LOWER:
case CLIPPING_UPPER: {
                    userPressedClipping();
                    break;
                }

答案 2 :(得分:2)

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

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

答案 3 :(得分:1)

是这样的:

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