在我看来,我所做的一切都是正确的,但是抛出了 NullPointerException 。我认为这与文件无关,因为会有 FileNotFoundException。 方法如下:
import java.util.Scanner;
import java.io.*;
public class InputFileData
{
public static Product [] readProductDataFile(File inputFile)
throws IOException
{
try
{
Scanner fileScan = new Scanner(inputFile);
int range = Integer.parseInt(fileScan.nextLine());
String codeData = fileScan.nextLine();
String priceData = fileScan.nextLine();
Scanner codeDataScan = new Scanner(codeData);
codeDataScan.useDelimiter("#");
Scanner priceDataScan = new Scanner(priceData);
priceDataScan.useDelimiter("#");
Product [] productRange = new Product[range];
for(int i = 0; i < range; i++)
{
productRange[i].setProductCode(codeDataScan.next());
productRange[i].setPricePerUnit(Integer.
parseInt(priceDataScan.nextLine()));
}
return productRange;
}
catch(NumberFormatException e)
{
System.out.println(e);
return null;
}
}
}
在我使用的主要方法中:
try
{
File productData = new File("productData.txt");
Product [] consideredRange = InputFileData.readProductDataFile(productData);
for(int i = 0; i < consideredRange.length; i++)
System.out.println(i + "./n" + consideredRange[i]);
}
catch(Exception e)
{
System.out.println(e);
}
文件中的数据如下所示:
10
PA/1234#PV/5732#Au/9271#DT/9489#HY/7195#ZR/7413#bT/4674#LR/4992#Xk/8536#kD/9767#
153#25#172#95#235#159#725#629#112#559#
Line 1 - number of items
Line 2 - Product code
Line 3 - price
那怎么了?
谢谢!
编辑:
at Assignment2.InputFileData.readProductDataFile(InputFileData.java:35) at Assignment2.InputFileData.readProductDataFile(InputFileData.java:35)
at Assignment2.MainTest.main(MainTest.java:211)
第35行是productRange[i].setProductCode(codeDataScan.next());
解决方案:
productRange[i] = new Product(codeDataScan.next(), Integer.parseInt(priceDataScan.next()));
最佳答案
您永远不会初始化productRange
数组的内容
Product [] productRange = new Product[range];
创建一个能够包含 Product
的数组,其元素全部为 null
然后您尝试“修改”每个元素...
for(int i = 0; i < range; i++)
{
productRange[i].setProductCode(codeDataScan.next());
productRange[i].setPricePerUnit(Integer.
parseInt(priceDataScan.nextLine()));
}
您出现 NPE 的可能原因是什么
在初始化数组之前,您需要先初始化数组的元素
for(int i = 0; i < range; i++)
{
productRange[i] = new Product();
productRange[i].setProductCode(codeDataScan.next());
productRange[i].setPricePerUnit(Integer.
parseInt(priceDataScan.nextLine()));
}
在诊断这些类型的问题时,您可以使用 System.out.println(或适当的记录器)来帮助您识别问题区域并使用调试器检查问题的状态(和流程)你的程序。
关于java - 调用静态方法进行数据输入时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29291927/