2

I'm writing Java on Windows 7, and I want to be able to work with the input from the keyboard, which I can only presume is the standard input.

I've tried to use BufferedInput, System.in, and Scanner, but all of them require the program to pause and wait for an end of line or return! Is there anyway to just collect and record the data as it is used, and not have to wait for a return?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Arcym
  • 500
  • 4
  • 13
  • 2
    You can create a new Thread and ask for inputs in this new Thread while doing something else in the main Thread. – grandouassou Feb 19 '12 at 11:44
  • *"not have to wait for a return* I (as a user) hit 'Return' when I am good and ready for the app. to do something with the data. What is the use-case for the application doing anything before that moment? What application feature are you trying to offer? – Andrew Thompson Feb 19 '12 at 11:59
  • I think I just understand the question from what you said Andrew. I don't think you can do what you want in console. – grandouassou Feb 19 '12 at 12:15
  • We learn stuff every day ! [interesting stuff](http://stackoverflow.com/questions/1066318/how-to-read-a-single-char-from-the-console-in-java-as-the-user-types-it) – grandouassou Feb 19 '12 at 12:23
  • That last link looks useful..! Thanks, Florian!! – Arcym Feb 22 '12 at 15:15

1 Answers1

3

Here is a quick solution:

public static void main(String[] args) {

    Thread inputThread = new Thread(new Runnable() {
        @Override
        public void run() {

            Scanner scan = new Scanner(System.in);
            String input = "";
            while (true) {
                System.out.println("Type something: ");
                input = scan.nextLine();
                System.out.println("Input: "+input);
            }
        }
    });

    inputThread.start();

    while (true) {

        System.out.println("");
        System.out.println("test");

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}

The main thread prints "test" every second. And the inputThread asks the user to type something then prints what he wrote. It's just a "visual" solution, you certainly don't want to print something while the user is typing.

grandouassou
  • 2,500
  • 3
  • 25
  • 60