在逗号之前获取数组列表中的第一个值

时间:2017-09-26 22:51:47

标签: java csv arraylist comma

我的程序正在读取外部文件并将每行数据放入数组列表中。外部文件中的一行有5个不同的值,值以逗号分隔。我只是无法弄清楚如何在数组列表中获取第一个值以用于我的代码的其他部分。 文件中的第一个值是名称,这就是我想要将它与它们为changeName创建的条目匹配。

System.out.println("Enter the name of the player you would like to change the amount for");
    String changeName = FileUtility.getInput().nextLine();

    Scanner s = new Scanner(new File(FILE_NAME));
    String str = "";
    ArrayList<String> list = new ArrayList<String>();

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

1 个答案:

答案 0 :(得分:0)

好的,如果我说得对,这将做你想做的事:

        Scanner s = new Scanner(new File("test.txt"));
        String str = "";
        List<List<String>> list = new ArrayList<List<String>>();

        while (s.hasNext()) {
            list.add(Arrays.asList(s.nextLine().split(",")));
        }

        // then you can acces random element from the list this way
        System.out.println(list.get(0).get(1));

        // or print all values in the list
        for (List<String> elem : list) {
            System.out.println(Arrays.toString(elem.toArray()));
        }

输出:

asdf
[asdf, asdf, asdf, asdf, asdf]
[asdf, asdf, asdf, asdf, asdf]

我的test.txt

asdf,asdf,asdf,asdf,asdf
asdf,asdf,asdf,asdf,asdf