Make the console wait for a user input to close

后端 未结 8 948
遥遥无期
遥遥无期 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();
        }
    }
    
    0 讨论(0)
  • 2020-11-30 02:20

    A simple trick:

    import java.util.Scanner;  
    
    /* Add these codes at the end of your method ...*/
    
    Scanner input = new Scanner(System.in);
    System.out.print("Press Enter to quit...");
    input.nextLine();
    
    0 讨论(0)
提交回复
热议问题