简体   繁体   中英

Switch/Case console menu in Java

Sup, everybody. I got a trouble with switch/case menu in Java.

class ConsoleMenu{
    ConsoleMenu(){
    }
    void ShowMenu(){
        System.out.println(1);
        System.out.println(2);
        System.out.println(3);
    }
}
public class Main {
    public static void main(String[] args) throws java.io.IOException {
        ConsoleMenu cs = new ConsoleMenu();
        char ch;
        do {
            cs.ShowMenu();
            ch = (char) System.in.read();
            switch (ch) {
                case '1':{
                    System.out.println("228");
                    break;}
                case '2':{
                    System.out.println("556");
                    break;}
            }
        } while (ch != '0');
    }
} 

When I make choice, it does something like that:

1
2
1
228
1
2
1
2
2
556
1
2
1
2

So i cannot undestand why Java shows me menu twice after completing the case. Any suggestions?

This line reads every character you type including new line '\\n' when you press enter

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

A simple solution would be to do another read and discard the result. Eg

    do {
        cs.ShowMenu();
        ch = (char) System.in.read();
        switch (ch) {
        case '1': {
            System.out.println("228");
            break;
        }
        case '2': {
            System.out.println("556");
            break;
        }
        }
        System.in.read();
    } while (ch != '0');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM