本文介绍了在Java中输入Ctrl + D时如何退出程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是我的反向波兰语计算器的一部分.

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 add another condition: if + is pressed by the user, the program exits.

我在网上看过,但似乎找不到任何解决方案.有任何想法吗?谢谢.

I've had a look online but can't seem to find any solutions. Any ideas? Thanks.

Scanner mySc = new Scanner(System.in);
//If input is an integer, push onto stack.
 if (mySc.hasNextInt()) {
    myStack.push(mySc.nextInt());
}
//Else if the input is an operator or an undefined input.
else if (mySc.hasNext()) {
    //Convert input into a string.
    String input = mySc.nextLine();
    //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);
    }**

推荐答案

尝试一下:

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

在这种情况下,当您按 + 时,循环将停止,这是因为 + 将EOF信号发送到-1System.in InputStream.在* nix系统上就是这种情况,对于Windows系统,使用 + 组合键发送EOF信号

In this case the loop will stop when you press + that is because + 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 + key combination

这篇关于在Java中输入Ctrl + D时如何退出程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 23:55