开发者

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.


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.


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());


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜