94

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.

The thing is, if I just "let it run", the output message will be printed but the console will close shortly afterwards, leaving no time to read the message.

As far as I remember, in C++, every console application will end with a "press any key to exit" or something like that. In C# I can simulate this behavior with a

Console.ReadKey();

But how can I do it in Java? I'm using the Scanner class, but given that "input" is my instance of Scanner:

input.next()
System.exit(0);

"Any key" will work, except for return, which is quite a big deal here. Any pointers?

Draken
  • 3,134
  • 13
  • 34
  • 54
makoshichi
  • 2,310
  • 6
  • 25
  • 52

8 Answers8

122

In Java this would be System.in.read()

x4u
  • 13,877
  • 6
  • 48
  • 58
  • 21
    This satisfies "Press enter to exit" but not "Press any key to exit", since it will not continue until the enter key is pressed. – Niall Thomson May 17 '11 at 14:26
  • I suppose "press enter to exit" is still better than "press any key EXCEPT enter to exit". Thanks, that will do for me. – makoshichi May 17 '11 at 14:38
  • 2
    @marcolopes I'm a bit late to the party, but since you're asking about an app, I'm guessing the problem is that you're having the user hit the enter key in the GUI or somewhere else within the app. They need to hit the enter key in the console, which will most likely only be visible if you are running it within an IDE. You'll need a different solution if you want to press enter within an app. – Thunderforge Sep 18 '13 at 02:09
  • 4
    System.in.read() reads exactly one byte, but ENTER may produce 1 or more bytes on different platforms, remember CRLF on Windows. So it may be that subsequent calls of read directly return LF from CRLF of the first call and therefore the app doesn't wait at all for input. – Thorsten Schöning Dec 08 '15 at 11:59
  • 2
    adding `import java.io.IOException;` is also required. – yu yang Jian Jan 02 '21 at 10:00
28

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();
    }
}
Petr
  • 62,528
  • 13
  • 153
  • 317
12

The problem with Java console input is that it's buffered input, and requires an enter key to continue.

There are these two discussions: Detecting and acting on keyboard direction keys in Java and Java keyboard input parsing in a console app

The latter of which used JLine to get his problem solved.

I personally haven't used it.

Community
  • 1
  • 1
Reverend Gonzo
  • 39,701
  • 6
  • 59
  • 77
11
public static void main(String args[])
{
    Scanner s = new Scanner(System.in);

    System.out.println("Press enter to continue.....");

    s.nextLine();   
}

This nextline is a pretty good option as it will help us run next line whenever the enter key is pressed.

Ardent Coder
  • 3,777
  • 9
  • 27
  • 53
Pranjal Gupta
  • 581
  • 7
  • 10
10

You can just use nextLine(); as pause

import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);

void Read()
{
     System.out.print("Press any key to continue . . . ");
     scan.nextLine();
}

However any button you press except Enter means you will have to press Enter after that but I found it better than scan.next();

Community
  • 1
  • 1
MohammadAmin98
  • 117
  • 1
  • 2
5

I used simple hack, asking windows to use cmd commands , and send it to null.

// Class for Different hacks for better CMD Display
import java.io.IOException;
public class CMDWindowEffets
{
    public static void getch() throws IOException, InterruptedException
    {
        new ProcessBuilder("cmd", "/c", "pause > null").inheritIO().start().waitFor();
    }    
}
Anton Kasiyn
  • 51
  • 1
  • 1
3

I've put in what x4u said. Eclipse wanted a try catch block around it so I let it generate it for me.

try {
        System.in.read();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

It can probably have all sorts of bells and whistles on it but I think for beginners that want a command line window not quitting this should be fine.

Also I don't know how common this is (this is my first time making jar files), but it wouldn't run by itself, only via a bat file.

java.exe -jar mylibrary.jar

The above is what the bat file had in the same folder. Seems to be an install issue.

Eclipse tutorial came from: http://eclipsetutorial.sourceforge.net/index.html

Some of the answer also came from: Oracle Thread

dim_voly
  • 478
  • 2
  • 10
  • 20
1

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