我试图提示用户输入信息并将其写入文本文件,然后程序从文本文件中读取,并且有一个计数器确定数组记录的长度。但是我目前停留在如何在不定义数组位置的情况下将每个字段存储到记录数组中。到目前为止,它从文本文件中读取是成功的,但是当我写入该文本文件时,会出现空指针异常错误。
这是我的代码片段
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();
}
最佳答案
是否有特定原因导致您不能只使用 ArrayList
?读取整个文件一次,只是为了确定数组的大小,然后再次读取它以获得记录的实际值,这似乎很浪费。
关于java - 如何在不定义数组位置的情况下将记录数组存储到每个字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45529612/