3

is there a way in Java to read input from console one word at a time? As in when user presses a space I want to take whatever word he typed before it and add it to a collection for example.

I've tried using Scanner, but it only allows me to read words after the end of a line (enter key press).

Context: It's a school project and teacher wants us to make a program that reads users input in one thread and displays list of words and their count from the input in another thread. And he wants the list updated after every new word is typed...

  • Are you simply trying to accept multiple command line arguments i.e. “java Foo a b c”? – JBallin May 04 '18 at 05:47
  • I don’t have experience with the console, but I would use “args” in the main function to access the arguments array and loop through it and add each argument to my collection. – JBallin May 04 '18 at 05:55

2 Answers2

2

You cannot do that via the console unless you put the console into character mode, see: https://stackoverflow.com/a/1066647/6391367

However I very much doubt that your teacher expects you to do that.

The two options I see are:

  1. Your teacher expects you to press enter after each word (check your spec carefully, or just ask them)
  2. Your teacher expects you to create a GUI using Swing / JavaFX where the user inputs text. Using a key listener you could then read this input character by character.
explv
  • 2,709
  • 10
  • 17
0

You should be able to read a single word from the console using Scanner. For example:

Scanner input = new  Scanner(System.in);
   String word;

    System.out.println("Enter word(s)");

    while(input.hasNext()){
    word = input.next();
    System.out.println(word);
    }
Jared
  • 1
  • 2