简体   繁体   中英

How to print a linked list into a file

Each linkedlist has a ISBN, authors name, book date, book price and I'm trying to save the whole book catalog (x many books) as a file. They said there is an error at

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)

which java:167 = for(Book newBook: g.SaveFile())

Here is the code:

from class 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());

}

from class 2:

count is a global var that keeps how many books are in the catalog.

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;

}

Your code is incomplete i cant make out what is head in your code. what

  cursor = cursor.getNext();
   bookCount[i] = out;

How cursor will become null ultimately your while loop is running infinitely. Please check
and you have to careful with

Book[] bookCount = new Book[count-1]; 

here the size of array is also playing role check

Try changing book[] to ArrayList<Book> i,e change declaration

Book[] bookCount = new Book[count-1]; 

to ArrayList<Book> bookCount = new ArrayList<Book>(); and change code bookCount[i]=cursor to bookCount.add(cursor)

and try

otherwise change

 Book[] bookCount = new Book[count]; 

and check

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 21

This exception only displays if you've gone beyond the arrays range. So for the while loop you want to do something like this

while (cursor < counter)//Or something
......

Does this make sense?

There's a problem with your count variable in class2 . How did you initialize it? The exception is coming because your array is of size 20 and you are inserting a Book at index 21

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM