简体   繁体   English

扫描程序仅读取文本文件的第一行

[英]Scanner read only the first line of a textual file

This is my code 这是我的代码

    public static void main(String[] args) {

    File source = //


    Scanner s = null;       
    int lineNumber =0;
        ArrayList<ArrayList<Integer>> tagsArray = new ArrayList<>();
    try {

        s= new Scanner(source);
    while (s.hasNext()) {

            String[] cols = s.nextLine().split("    ");

            for (int i = 0; i < cols.length; i++) {
                if (cols[i].equals("1"))
                    tagsArray.get(i).add(lineNumber);
                }
            lineNumber++;

        }   
    } catch (Exception e) {
        // TODO: handle exception
    }
}

When I delete the for statement it read the whole text file but when I use it it read only the first line why? 当我删除for语句时,它将读取整个文本文件,但是当我使用它时,它仅读取第一行,为什么?

I guess you get an Exception , but you catch and hide it instead of handling it. 我猜您会收到一个Exception ,但是您捕获并隐藏了它,而不是处理它。 This is very bad! 这真是太糟了! You should at least print the stacktrace of the exception. 您至少应该打印异常的堆栈跟踪。

You try to access: 您尝试访问:

tagsArray.get(i).add(lineNumber);

when tagsArray is empty. tagsArray为空时。 You need to instantiate each ArrayList<Integer> inside tagsArray before accessing it. 在访问它之前,需要实例化tagsArray每个ArrayList<Integer>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM