Java 在 switch 语句中使用系统读取



我正在使用System.in.read()尝试以下switch语句:

char ch1, ch2;
    ch1 = (char) System.in.read();
    switch(ch1) {
        case 'A':
            System.out.println("This A is part of outer switch.");
            ch2 = (char) System.in.read();
//                ch2 = 'A';
            switch(ch2) {
                case 'A':
                    System.out.println("This A is part of inner switch");
                    break;
                case 'B':
                    System.out.println("This B is part of inner switch");
                    break;
            } // end of inner switch
            break;
        case 'B': // ...

ch2 = (char) System.in.read();

似乎没有被执行,除非明确声明ch2 = 'A',否则内部switch语句不会被执行。那么如何使第二个read()起作用呢?

好吧,不得不做一些实验,但我敢打赌你在输入第一个字符后按回车键? 如果是,则 ch2 将设置为该击键。

您可以做的是在获得第一个字符后立即System.in.skip(1)告诉输入流跳过它。 然后,设置 ch2 的调用将完美运行。 可能有很多更好的方法来读取输入,但是由于每次输入字符时,您都会输入两个字符,并且需要跳过最后一个字符。

所以重申一下:

ch1 = (char) System.in.read();
System.in.skip(1);//Skip the next keystroke, which is enter
switch(ch1) {
    case 'A':
        System.out.println("This A is part of outer switch.");
        ch2 = (char) System.in.read();
//                ch2 = 'A';
        switch(ch2) {

最新更新