[英]Having trouble parsing multiple files and storing in array in Java
我試圖創建一個類,該類采用一定數量的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;
}
}
}
}
}
您看到NPE的原因是j=1
代碼在i=1
之前運行,因此scanner[1]
還不存在。
最好分別處理每個文件並在以后合並值。 這還將使您的閱讀代碼與計算結果分離開來,從而使查找將來的錯誤更加容易。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.