我需要讀取文件的某些部分並將其放入正確的數組中。嘗試讀取文件並將值放入數組
public static void load(String fileName, String[] itemNumbers,
String[] itemNames, double[] priceOfItem, int[] quantity) throws IOException{
int i = 0;
File inFile = new File(fileName);
Scanner reader = new Scanner(inFile);
while(reader.hasNext()){
itemNumbers[i] = reader.next();
itemNames[i] = reader.next();
priceOfItem[i] = reader.nextDouble();
quantity[i] = reader.nextInt();
i++;
}
//This is just to see if it worked
System.out.println(itemNumbers[i]);
System.out.println(itemNames[i]);
System.out.println(priceOfItem[i]);
System.out.println(quantity[i]);
}
這是我正在閱讀的文件。
E3233 CordlessDrill 129.99 12
W2321 WindowSealer 3.39 84
該數組與文件部分按順序排列。 當我運行此我收到以下
null
null
0.0
0
循環結束後,變量'i'指向數組中未使用的位置(因此是數組的第一個未使用的位置)。因此,在'System.println.out(itemNumbers [i-1])'中使用'i-1'(如果你可以改變接口,你應該使用列表:它們可以動態增長,而數組有固定大小,導致您想要閱讀更多項目的情況,但是陣列中沒有空閒插槽)。 – sleepy42
謝謝,我不能相信我錯過了。現在非常明顯! –