Make the console wait for a user input to close

后端 未结 8 983
遥遥无期
遥遥无期 2020-11-30 01:49

I have a console application that after performing its tasks, must give feedback to the user, such as \"operation completed\" or \"operation failed\" and the detailed error.

8条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-30 02:15

    I'd like to add that usually you'll want the program to wait only if it's connected to a console. Otherwise (like if it's a part of a pipeline) there is no point printing a message or waiting. For that you could use Java's Console like this:

    import java.io.Console;
    // ...
    public static void waitForEnter(String message, Object... args) {
        Console c = System.console();
        if (c != null) {
            // printf-like arguments
            if (message != null)
                c.format(message, args);
            c.format("\nPress ENTER to proceed.\n");
            c.readLine();
        }
    }
    

提交回复
热议问题