我试图提示用户输入信息并将其写入文本文件,然后程序从文本文件中读取,并且有一个计数器确定数组记录的长度。但我目前坚持如何将每个字段存储到一个记录数组中,而无需定义数组的位置。到目前为止,它成功地从文本文件中读取,但是当我写入该文本文件时,将会出现空指针异常错误。如何将记录数组存储到每个字段中而不必定义数组位置?
这是我的代码
static class publisherDetails
{
String pubID;
String publisher;
String pubAddress;
}
public static void publisherDetails() throws IOException
{
File publisherMain = new File("publisherMain.txt");
Scanner readpublisher = new Scanner(publisherMain);
publisherDetails [] publisherList = new
publisherDetails[countPubLines(0, publisherMain)];
createPublisher(publisherList, publisherMain, readpublisher);
readpublisher.close();
printPublisher(publisherList);
}
public static int countPubLines(int count, File publisherMain) throws IOException
{
Scanner countingLines = new Scanner(publisherMain);
while (countingLines.hasNextLine())
{
String reading = countingLines.nextLine();
count++;
}
countingLines.close();
count = count/3;
return count;
}
public static void createPublisher(publisherDetails[] publisherList, File publisherMain, Scanner readpublisher) throws IOException
{
while (readpublisher.hasNextLine())
{
for (int i=0; i< publisherList.length; i++)
publisherList[i] = new publisherDetails();
{
publisherList[0].pubID = readpublisher.nextLine();
publisherList[0].publisher =readpublisher.nextLine();
publisherList[0].pubAddress =readpublisher.nextLine();
publisherList[1].pubID =readpublisher.nextLine();
publisherList[1].publisher =readpublisher.nextLine();
publisherList[1].pubAddress =readpublisher.nextLine();
publisherList[2].pubID =readpublisher.nextLine();
publisherList[2].publisher =readpublisher.nextLine();
publisherList[2].pubAddress =readpublisher.nextLine();
publisherList[3].pubID =readpublisher.nextLine();
publisherList[3].publisher =readpublisher.nextLine();
publisherList[3].pubAddress =readpublisher.nextLine();
}
}
readpublisher.close();
}
public static void printPublisher(publisherDetails[] publisherList)
{
for (int j=0 ;j<publisherList.length; j++)
{
output("Publisher ID : " + publisherList[j].pubID);
output("Publisher : " + publisherList[j].publisher);
output("Publisher Address : " + publisherList[j].pubAddress);
}
}
public static void addPublisher() throws IOException
{
FileWriter inputPublisher = new FileWriter(new File("publisherMain.txt",true);
newPublisher(inputPublisher);
}
public static void newPublisher(FileWriter inputPublisher) throws IOException
{
Scanner scan = new Scanner(System.in);
output("Please enter publisher ID");
String ID = scan.nextLine();
inputPublisher.write("\n"+ID);
output("Please enter Publisher ");
String publisher = scan.nextLine();
inputPublisher.write("\n"+publisher);
output("Please enter publisher Address");
String pubAddress = scan.nextLine();
inputPublisher.write("\n"+pubAddress);
scan.close();
inputPublisher.close();
}
请花更多的精力来设置代码的格式。目前*真的很难阅读,并且到处都有缩进。我强烈怀疑你并不需要~100行代码来证明这个问题,请将它降低到[mcve]。 –
(我强烈建议你更仔细地遵循Java命名约定 - 'publisherList'不是传统的类名。) –
@JonSkeet指出,谢谢!我很新,所以请原谅我,我一定会在下一次考虑到这一点! :D – lyrehcx