Search code examples
javaswitch-statementjava-iosystem.in

Java use system read in switch statements


I am trying the following switch statements using 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 seems to be executed, and unless explicitly state ch2 = 'A', the inner switch statements will not be executed. So how to make the second read() work?


Solution

  • Okay, had to do some experimenting, but I bet you're hitting enter after you input the first character? If you are, then the ch2 is being set to that keystroke.

    What you can do is tell the input stream to skip that by going System.in.skip(1) right after you get the first character. Then the call to set ch2 will work perfectly. There are probably lots of better ways to read the input, but since every time you are entering in a character, you are entering two and need to skip the last one.

    So to reiterate:

    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) {