0

I am currently working on a program that will ask the user for their array length, then asks the user to input many single words (asking one at a time for each word), then storing each word in a String array of the length determined by the user. I then want the program to print out the array of words in its entirety at the end. HOWEVER, when my program prints it asks the user to enter their array size in twice before they can answer once EX: Please enter an array size:Please enter an array size: ____, also when printing the array it is printed like this [, string, string] there is a comma and a space before the words even appear! Could you please take a look at my code! Thank you so much for your help!!

import java.util.Scanner; 
import java.util.ArrayList;

public class UserWords  
  {
    public static void main(String[] args)
    {
    Scanner scan = new Scanner(System.in);
    System.out.println("Please enter in the length of your array: ");
    int x = scan.nextInt();
    ArrayList<String>words=new ArrayList<String>();

    for (int i = 0; i <= x; i++ ) {
      System.out.print("\nPlease enter a word: ");
      String s = scan.nextLine();
      words.add (s);
    }
    System.out.println(words);

  }
}
John burks
  • 13
  • 2
  • If I am being honest I am also not entirely sure how the method.add(variable) works in my program if anyone had any insight to what it does I would be very appreciative. I wrote it down in class, but it was never fully explained. – John burks Jun 19 '18 at 01:19
  • `System.out.println(words);` is simply using `ArrayList`'s implementation of `toString` to print information about the class, this isn't going to magically print a list of the items, you're going to have to iterate over the list and print each element separately – MadProgrammer Jun 19 '18 at 01:20
  • @Johnburks Here are the docs on the `add()` method: https://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(E) – GBlodgett Jun 19 '18 at 01:22

0 Answers0