Search code examples
javalinked-listfileoutputstream

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;

}


Solution

  • 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