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

后端 未结 3 850
半阙折子戏
半阙折子戏 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

    I assume you are talking about a console application?

    On unix systems, pressing Ctrl+D closes the stdin for an application. This will result in the input stream underneath Scanner closing, which will cause mySc.hasNext() to return false.

    On windows, users need to press Ctrl+Z enter for the same effect.

    If the input stream has not been closed, then mySc.hasNext() will block until it can return true.

    So you need to wrap your program in a while(mySc.hasNext()) loop, e.g.

        public static void main(String[] args) {
    
            Scanner mySc = new Scanner(System.in);
    
            while(mySc.hasNext()) {
    
    //If input is an integer, push onto stack.
                if (mySc.hasNextInt()) {
                    System.out.println(String.format("myStack.push(%s);", mySc.nextInt()));
                }
    //Else if the input is an operator or an undefined input.
                else {
                    //Convert input into a string.
                    String input = mySc.nextLine();
                    System.out.println(String.format("input = %s", input));
    
                    //Read in the char at the start of the string to operator.
    //                char operator = input.charAt(0);
    //                if (operator == '=') {
    //                    //Display result if the user has entered =.
    //                }
    //            **else if ("CTRL-D entered") {
    //                System.exit(0);
    //            }**
                }
            }
        }
    

提交回复
热议问题