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 开发者_Go百科automatically end it when the return '\n' character is pressed at the end of the sentence.
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+")));
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!
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 :-)
精彩评论