Pandy
Pandy

Reputation: 55

Printing from an ArrayList

I'm taking in a text file and storing each word in an arraylist. However the problem is, when I iterate through the arraylist and print the contents, the words appear many times and not necessarily in the right order. Here's a snippet of the code below:

 public static void main(String args[])
    {
        try
        {
            ArrayList storeWord = new ArrayList();


            Scanner scannerWord = new Scanner(new File("word"));

            while(scannerWord.hasNext()) {
                String word = scannerWord.next();{
                    storeWord.add(word);

                    Iterator itr = storeWord.iterator();
                    while(itr.hasNext())
                        System.out.println(itr.next());

                }

Does anyone know what the problem could be and how to fix it? Thanks.

Upvotes: 1

Views: 475

Answers (3)

Colin
Colin

Reputation: 2021

Try this

public static void main(String args[]) { 
    ArrayList storeWord = new ArrayList();
    Scanner scannerWord = new Scanner(new File("word"));

    while(scannerWord.hasNext()) {
        storeWord.add(scannerWord.next());
    }

    Iterator itr = storeWord.iterator();
    while(itr.hasNext()){
       System.out.println(itr.next());
    }
}

Your 'print' loop was nested in your 'read' loop.

Upvotes: 5

jhlu87
jhlu87

Reputation: 4019

you need to take your iterator and printing while loop out of the original while loop

Upvotes: 1

TheClair
TheClair

Reputation: 721

You're printing out your entire list on every read. That could be why each word is displayed multiple times.

You might want:

Scanner scannerWord = new Scanner(new File("word"));

while(scannerWord.hasNext()) {
  String word = scannerWord.next();{
  storeWord.add(word);
}
Iterator itr = storeWord.iterator();
while(itr.hasNext())
  System.out.println(itr.next());

Upvotes: 3

Related Questions