Justin
Justin

Reputation: 27

Making strings entered add into an arraylist

I want the user input to be a string added to my array list each time the user inputs a new string. I think I am on the right track but I'm not entirely sure because I can't output my array. Here is my code.

System.out.println("input your word list");

Scanner scanner = new Scanner(System.in);
String phrase;
//not sure if phrase =""; is necessary but eclipse suggested it at one point
phrase = ""; 
ArrayList<String[]> wordlist = new ArrayList<String[]>();   

for(int i=0; i<phrase.length();i++){
  phrase = scanner.nextLine();
  wordlist.add(new String[] {phrase});
}

System.out.println(phrase);
System.out.println(Arrays.toString(wordlist));

Upvotes: 1

Views: 160

Answers (2)

user5342366
user5342366

Reputation:

Edit :- here you go this takes all input to array list until the user types quit and displays all the inputs:-

public static void main(String[] args)
{
     System.out.println("input your word list");

     Scanner scanner = new Scanner(System.in);
     ArrayList<String> wordlist = new ArrayList<String>();

     String input = "";
     while(!input.toLowerCase().equals("quit"))
     {
         input = scanner.nextLine();

         if(!input.toLowerCase().equals("quit"))
             wordlist.add(input);
     }

     for(int i = 0; i < wordlist.size(); i++)
     {
         System.out.println(wordlist.get(i));
     }
}

Upvotes: 1

Jonah Haney
Jonah Haney

Reputation: 521

Would using ArrayList<String> instead of ArrayList<String[]> be a possible solution? In that case you could just do something like this:

Scanner scan = new Scanner(System.in);
ArrayList<String> wordList = new ArrayList<String>();
for (int i=0; i<3; i++){       //not sure what you're doing with your loop
                               //so will just get 3 inputs
    wordList.add(scan.next());
}

Then to print them each out you would do:

for (int i=0; i<wordList.size(); i++){
    System.out.println(wordList.get(i));
}

OR if you prefer for-each:

for (String word : wordList){
    System.out.println(word);
}

Upvotes: 1

Related Questions