0

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

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();

not 似乎被执行,除非明确声明ch2 = 'A',否则内部switch语句将不会被执行。那么如何进行第二项read()工作呢?

4

1 回答 1

2

好的,必须做一些实验,但我敢打赌你在输入第一个字符后会按回车键?如果是,则 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) {
于 2014-11-20T00:30:13.627 回答