简体   繁体   English

在用户输入的Ctrl + Z上终止Java程序

[英]Terminate Java Program on Ctrl+Z input from user

I have following code: 我有以下代码:

        String inputString;
        Scanner in = new Scanner(System.in);
        while (true) {
            System.out.print("jcp>");
            inputString = in.nextLine();

            String[] tokens = inputString.split(" ");
            switch (tokens[0]) {
                case "new":
                    createNewInstance(tokens);
                    break;
                case "call":
                    callMethod(tokens);
                    break;
                case "print":
                    Object obj = hashMap.get(tokens[1]);
                    print(obj);
                    break;
                default:
                    System.out.println("Illegal command!");
                    break;
            }
        }

I simply want the program to break out of while loop when user hits ctrl+Z 我只是想让程序在用户按下ctrl + Z时退出while循环

nextLine() will throw NoSuchElementException when the stream has reached its end. 当流到达其末尾时, nextLine()将抛出NoSuchElementException Or you can use in.hasNextLine(). 或者,您可以使用in.hasNextLine().

Ctrl+Z to exit the program would be bad, Ctrl+C|Ctrl+D already ends the program execution on terminal, so it would be good the same way you expect users to type in commands, tell them to type exit as the command to EXIT your program and shortcuts like x or e can be used instead of complete word. Ctrl + Z退出程序是不好的,Ctrl + C | Ctrl + D已经在终端上结束了程序的执行,所以这与您希望用户键入命令的方式一样好,告诉他们键入exit作为命令退出程序,可以使用xe类的快捷方式代替完整的单词。

How about following code, 下面的代码怎么样?

String inputString;
Scanner in = new Scanner(System.in);
while (true) {
    System.out.print("jcp>");
    inputString = in.nextLine();
    String[] tokens = inputString.split(" ");
    switch (tokens[0]) {
        case "n":
        case "new":
            createNewInstance(tokens);
            break;
        case "c":
        case "call":
            callMethod(tokens);
            break;
        case "p":
        case "print":
            Object obj = hashMap.get(tokens[1]);
            print(obj);
            break;
        case "e":
        case "x":
        case "exit":
            return;
        default:
            System.out.println("Illegal command!");
            break;
    }
}

If return; 如果return; won't work you can replace that with System.exit(0); 您将无法使用System.exit(0);替换它System.exit(0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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