How to exit the program when Ctrl+D is entered in Java?

后端 未结 3 818
半阙折子戏
半阙折子戏 2021-01-22 18:21

Below is a section of my Reverse Polish Calculator.

If an integer is entered, push it to the stack and, if = is pressed, peek the result. However, I want to a

3条回答
  •  星月不相逢
    2021-01-22 18:52

    Try this:

    public static void main(String[] args) {
        try {
            byte[] b = new byte[1024];
            for (int r; (r = System.in.read(b)) != -1;) {
                String buffer = new String(b, 0, r);
                System.out.println("read: " + buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    In this case the loop will stop when you press CTRL+D that is because CTRL+D sends an EOF signal to the System.in InputStream which is -1. That is the case on *nix systems, for Windows system, the EOF signal is sent using the CTRL+Z key combination

提交回复
热议问题