我需要读取文件的某些部分并将其放入正确的数组中。尝试读取文件并将值放入数组
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
谢谢,我不能相信我错过了。现在非常明显! –