sjking
sjking

Reputation: 1290

Java Scanner, taking user input from console into array list as separate words

I am trying to read the user input from the console directly into an array list, separated by each word or entity that has whitespace on either side (the default behavior). The problem is I am stuck inside of a while loop. Scanner.next() keeps waiting for more input, though I know I want to stop feeding input after the user presses return:

Scanner input = new Scanner(System.in);

    System.out.print("Enter a sentence: ");
    do {
        if (words.add(input.next());

    } while (input.hasNext());

    System.out.println(words);

I input a line, except I will have to press CTRL-D to terminate it (IE. signal the end of input). I just want to automatically end it when the return '\n' character is pressed at the end of the sentence.

Upvotes: 0

Views: 9788

Answers (3)

Francisco Paulo
Francisco Paulo

Reputation: 6322

You could always use the Console class, like this:

Console console = System.console();

System.out.print("Enter a sentence: ");

List<String> words = Arrays.asList(console.readLine().split("\\s+"));

System.out.println(words);

The readline() method should take care of the \n issue.

If you require a Scanner for the type reading capabilities, you can mix both classes:

Scanner scanner = new Scanner(console.reader());

Hope this helps!

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

It may be simpler to use split for what you want.

// read a line, split into words and add them to a collection.
words.addAll(Arrays.asList(input.nextLine().split("\\s+")));

Upvotes: 2

TofuBeer
TofuBeer

Reputation: 61526

You could call input.hasNextLine and input.nextLine to get a line, and then create a new Scanner for the line you got and use the code that you have now. Not the cheapest solution, but an easy way to implement it until you come up with a better one :-)

Upvotes: 0

Related Questions