将 Java ArrayList 内容逐行打印到控制台 [英] Printing Java ArrayList contents line by line to console

查看:47
本文介绍了将 Java ArrayList 内容逐行打印到控制台的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Java 编程非常陌生,这实际上是我需要在家庭作业中解决的一个问题的一部分:我正在将文件的内容作为字符串逐行读取到 ArrayList 中以供以后处理.我需要程序打印出来以在单独的行上控制台 ArrayList 的内容,但是运行编译文件后的输出打印文件的第一行,然后在下一行打印第一行和第二行,然后打印程序的第一行、第二行和第三行.

I'm very new to Java programming, and this is actually part of a problem I need to solve for homework: I am reading the contents of a file line by line as a String into an ArrayList for later processing. I need the program to print out to console the contents of the ArrayList on separate lines, but the output after I run the compiled file prints the first line of the file, then prints the first and second lines together on the next line, then prints the first, second and third lines of the program.

我对这应该如何工作的理解是程序将获取我的文件,FileReader 和 BufferedReader 将获取文件中的文本行作为字符串,然后将它们放置在 ArrayList 中,每个字符串位于不同的位置在 ArrayList 中的位置对吗?有人可以告诉我在while循环中哪里出错了吗?谢谢!

My understanding of how this is supposed to work is that the program will take my file, the FileReader and BufferedReader will grab the lines of text in the file as Strings, which are then placed in the ArrayList with each String at a different position in the ArrayList right? Can someone please tell me where in the while loop I'm going wrong? Thanks!

代码:

public class ArrayListDemo

{
    public static void main (String[]args)
    {
    try
    {
        ArrayList<String> demo= new ArrayList <String>();
        FileReader fr= new FileReader("hi.tpl");
        BufferedReader reader= new BufferedReader(fr);
        String line;
        while ((line=reader.readLine()) !=null)
            {
            //Add to ArrayList
            demo.add(line);
            System.out.println(demo);
            }

        reader.close();
    }catch (Exception e)
        {
            System.out.println("Error: "+e.getMessage());
            System.exit(0);
        }
    }
}

获得的输出:

cat
cat, rat
cat, rat, hat

预期输出:

cat
rat
hat

推荐答案

您每次看到的输出都是 ArrayList.toString() 打印到标准输出的结果.相反,在将文件内容读入 ArrayList 后循环遍历 ArrayList:

The output you are seeing each time is the result of ArrayList.toString() being printed to standard out. Instead, loop through the ArrayList after you've finished reading the contents of the file into the ArrayList:

    while ((line=reader.readLine()) !=null) {            
        //Add to ArrayList
        demo.add(line);            
    }
    reader.close();
    //do fun stuff with the demo ArrayList here
    for (String s : demo) { System.out.println(s); }

这篇关于将 Java ArrayList 内容逐行打印到控制台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆