-1
Im在下面的代码中有一个空指针异常错误。空指针异常
Exception in thread "main" java.lang.NullPointerException
at BookTest.createInstances(BookTest.java:53)
at BookTest.main(BookTest.java:20)
我真的可以使用一些帮助,我一直坚持了很长一段时间。
import java.io.*;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class BookTest
{
public static void main (String[] args){
ArrayList list = createInstances();
writeFile(list);
}
public static ArrayList<Book> createInstances()
{
ArrayList<Book> bookArray = new ArrayList<Book>();
String inputArray[] = new String [10];
int i = 0;
Scanner input;
// Read the text file and stores into inputArray where each line is stored as String.
try
{
input = new Scanner(new File("book.txt"));
input.useDelimiter("\n");
while (input.hasNext()){
inputArray[i]=input.next();
i++;
}
// dataArray defines the two dimensional array that store all the values in the line.
String dataArray [] [] = new String [10] [11];
System.out.println(inputArray.length);
for (int k =0; k<inputArray.length; k++){
String getLine = inputArray[k];
String[] eachLine =getLine.split(" ");
int length = eachLine.length;
for (int j=0; j<length;j++){
dataArray [k][j]= eachLine[j];
}
}
for (int l = 0; l < 10; l++)
{
if (dataArray[l][0].equals("Fiction"))
{
Publisher p = new Publisher(dataArray[l][3], dataArray[l][4]);
bookArray.add(new Fiction(dataArray[l][1], dataArray[l][2], dataArray[l][5],
p, Double.parseDouble(dataArray[l][6]), dataArray[l][7], l));
}
else
{
Publisher p = new Publisher(dataArray[l][3], dataArray[l][4]);
bookArray.add(new NonFiction(dataArray[l][1], dataArray[l][2],dataArray[l][5],
p, Double.parseDouble(dataArray[l][6]), dataArray[l][7], l));
}
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
return bookArray;
}
public static void writeFile(ArrayList arrayOfBook)
{
Formatter output ;
try
{
output = new Formatter("book.txt");
for(int i = 0; i<11;i++)
{
output.format("%s %s %s %s %s %s %s %s %s %s %s \n", arrayOfBook.get(i));
}
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
这是文件即时试图读取
小说AbrahamLincolnVampireHunter格雷厄姆 - 史密斯威利NY 978-0446563079 13.99 222真正的12 1/1/2015
小说科学怪人雪莱普雷斯科特GA 978-0486282114 7.99 321真8 2008年5月12日
非小说类作品LifeofKennedy琼斯皮尔逊MT 758-29304566 12.90传记3 11/11/2011
您确定为'inputArray'的每个元素赋值吗? – fabian
在这里,我正在研究一个详细的答案,只是为了注意到这个问题已经在我想发布我的答案之前关闭。 – mezzodrinker