0

I am trying to list the components of an array that is created from Scanner input. Example...

 System: Enter a list of words:

 User: The weather is nice today

 System: [The, weather, is, nice, today]

My code is as follows,

import java.util.ArrayList;
import java.util.Scanner;
public class ArrayListPractice
{
    public static void main(String[] args)
    {
        ArrayList<String> word=new ArrayList<String>();
        System.out.println("Enter a list of words:");
        Scanner keyboard = new Scanner(System.in);    
        String n = keyboard.next();
       
        while(keyboard.hasNext()){
            word.add(keyboard.next());
        }
        System.out.println(word);
   }
}

My problem is that the scanner keeps waiting for input and therefore doesn't display any output. I've also tried different for-loops but haven't been able to figure those out. An example of one I've tried is listed below. This one only displays the first two words inputted by the user

        for (int i=0; I<n.length(); i++){
            word.add(n);
            n = keyboard.next();
        }
        System.out.println("a) \n"+word);

Any tips would be greatly appreciated, thank you in advance!

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197

1 Answers1

2

You don't need the while loop here. Just take the line of the user's input as a String and then you can split it into an array of words using String.split().

System.out.println("Enter a list of words:");
Scanner keyboard = new Scanner(System.in);    
String line = keyboard.nextLine();
String[] words = line.split(" ");

for (String word : words)
 System.out.println(word);

Output:

Enter a list of words:
Hello I am who I am
Hello
I
am
who
I
am

Alternative for coding class

System.out.println("Enter a list of words:");
Scanner keyboard = new Scanner(System.in);    
ArrayList<String> words = new ArrayList<>();

String word = "quit";

do{
    word = keyboard.next();

    if (!word.equals("quit"))
        words.add(word);

}while (!word.equals("quit"));

for (String w : words)
    System.out.println(w);
Themelis
  • 4,048
  • 2
  • 21
  • 45