在使用字符串读取txt文件时获取重复输出,将它们放入arraylist-Java中

时间:2016-02-21 19:58:15

标签: java arraylist

我有一个txt文件:

it was the best of times it was the worst of times
it was the age of wisdom it was the age of foolishness
it was the epoch of belief it was the epoch of incredulity
it was the season of light it was the season of darkness
it was the spring of hope it was the winter of despair

我希望将它们分成1个arraylist,每个单词用逗号分隔。到目前为止,我有这个:

import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;

public class arraylist{
    public static void main(String[] args) {
        try {
            Scanner s = new Scanner(new File("tinyTale.txt"));
            ArrayList<String> list = new ArrayList<String>();

            while (s.hasNext()){
                list.add(s.next());
                System.out.println(list);
            }
            s.close();
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}

作为输出,我得到了:

[it]
[it, was]
[it, was, the]
[it, was, the, best]
[it, was, the, best, of]
[it, was, the, best, of, times]
[it, was, the, best, of, times, it]
[it, was, the, best, of, times, it, was]
[it, was, the, best, of, times, it, was, the]
[it, was, the, best, of, times, it, was, the, worst]
[it, was, the, best, of, times, it, was, the, worst, of]
[it, was, the, best, of, times, it, was, the, worst, of, times]
[it, was, the, best, of, times, it, was, the, worst, of, times, it]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom, it]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom, it, was]
[it, was, the, best, of, times, it, was, the, worst, of, times, it, was, the, age, of, wisdom, it, was, the]

...并继续其余的内容,所以每次有空间时它都会重新开始...所以它打印出来的最后一件事就是我需要的东西。 任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:3)

这是因为你的println语句在循环中。将System.out.println(list);移到while循环之外以查看所需的输出。

答案 1 :(得分:3)

这只是因为在循环完成之前,在循环的每次迭代中打印列表的完整内容。

如果您只想打印列表的最终内容,请在循环后打印:

while (s.hasNext()){
    list.add(s.next());
}
System.out.println(list);