解析多个文件并在Java中存储在数组中时遇到问题

时间:2014-11-25 14:46:27

标签: arrays parsing loops

我正在尝试创建一个类,它接受一定数量的相同格式的ppm文件(由用户在包含main方法的类中输入),然后逐个比较每个文件中的相应整数一,将它们存储在一个临时数组中,以便对它们进行排序,并可以取中值并写入新的ppm文件,最终创建一个新的图像。

例如,如果我有3个文件,我想要获取每个文件的第一个整数值(在标题的3行之后),将每个值存储在临时数组中(在本例中为3)以进行比较然后我想用每个文件中的第二个值和第三个等来做同样的事情。这就是我所坚持的。现在我设置它的方式是导致空指针异常,但我尝试了其他各种已经运行但导致错误结果的东西。有什么建议吗?

import java.io.File;
import java.io.IOException;
//import java.io.PrintWriter;
import java.util.Scanner;
import java.util.Arrays;

public class Effects {


public Effects() throws IOException{}


public void filter(File[] files, String outputFileName) throws IOException {

    //Create an array of Scanners equal to the number of files
    Scanner[] scanner = new Scanner[files.length];

    //Create a scanner that is linked to each file that must be read
    for(int i=0; i<scanner.length; i++) {
        Scanner scan = new Scanner(files[i]);
        scanner[i]=scan;

        //For each scanner, first skip the first 3 lines of text, then take one integer from
        //file and store it in the temporary array compare [such that the integer parsed
        // by scanner[0] is stored at compare[0] and so on.
        while(scan.hasNext()) {
            int [] compare = new int [scanner.length-1];
            boolean header = true;

            for(int j=0; j<files.length; j++) {
                while(header==true) { 
                    //the first 3 lines in each document need to be skipped before the integer values of relevance begin.
                    scanner[j].nextLine();
                    scanner[j].nextLine();
                    scanner[j].nextLine();

                    header = false;
                }

                int value = scanner[j].nextInt(); //NULL POINTER EXCEPTION
                compare[j] = value;
            }

        }            
    }    
}

}

1 个答案:

答案 0 :(得分:0)

您看到NPE的原因是j=1代码在i=1之前运行,因此scanner[1]尚不存在。

最好分别处理每个文件并稍后组合这些值。这也会将您的阅读代码从您的计算中分离出来,从而更容易追踪任何未来的错误。

相关问题