0

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;

}

Allen Tran
  • 49
  • 7

3 Answers3

1

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

harsha kumar Reddy
  • 1,251
  • 1
  • 20
  • 32
0

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?

Dajan3
  • 23
  • 5
  • `cursor` is of type `Book` and `counter` is an integer type, so this comparison doesn't make sense – UnholySheep Mar 19 '17 at 18:03
  • I was using that as an example. From what I understand they need to have a while(a < b) sort of loop to prevent the loop from accessing something that's not in the loop – Dajan3 Mar 19 '17 at 18:18
0

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