每个链表都有一个ISBN,作者姓名,书籍日期,书籍价格,我正在尝试将整个书籍目录(x本书)保存为一个文件。他们说发生错误
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 21
at BookCatalog.SaveFile(BookCatalog.java:34)
at BookCatalogClient.menu(BookCatalogClient.java:167)
at BookCatalogClient.main(BookCatalogClient.java:25)
哪个java:167 = for(预订newBook:g.SaveFile())
这是代码:
来自第1类:
PrintStream out = new PrintStream(new FileOutputStream("books.txt"));
for(Book newBook: g.SaveFile()){
out.println(newBook.getBookISBN()+"\t"+newBook.getLastName()+"\t"
+newBook.getFirstName()+"\t"+newBook.getTitle()+"\t"+newBook.getYearOfPublication()+"\t"+newBook.getPrice());
}
来自第2类:
count是一个全局变量,用于保存目录中有多少本书。
public Book[] SaveFile(){
Book cursor = head;
Book[] bookCount = new Book[count-1];
int i = 0;
while(cursor!=null){
Book out = cursor;
cursor = cursor.getNext();
bookCount[i] = out;
i++;
}
return bookCount;
}
最佳答案
您的代码不完整,我无法确定您的代码中的head
是什么。什么
cursor = cursor.getNext();
bookCount[i] = out;
游标最终将如何变为null,而while循环无限运行。请检查
而你必须小心
Book[] bookCount = new Book[count-1];
这里数组的大小也起着作用
尝试将book []更改为
ArrayList<Book>
,即更改声明Book[] bookCount = new Book[count-1];
到
ArrayList<Book> bookCount = new ArrayList<Book>();
并将代码
bookCount[i]=cursor
更改为bookCount.add(cursor)
并尝试
否则改变
Book[] bookCount = new Book[count];
并检查
关于java - 如何将链接列表打印到文件中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42890009/