Invoking an object`s method inside a for loop.

ZKR

Honorable
Mar 12, 2012
35
0
10,580
Hey guys. Need your help again.
I have to make a Library that contains books.
In the Library class, a method called mostPagesBook, returns the book with most pages. It compiles, but errors when run:

Exception in thread "main" java.lang.NullPointerException
at Library.mostPagesBook(Library.java:32)
at TEMP.main(TEMP.java:29)
(POINTING AT THE pages = checkBook.getNumPages(); Line)


In Library:
Code:
public Book mostPagesBook ()
	{
		int bookNumber = 0, pages, mostPages = 0, largestBook = 0;
		for (Book checkBook : bookList)
		{	
			pages = checkBook.getNumPages();
			if (pages > mostPages)
			largestBook = bookNumber;
			bookNumber++;												
		}	
		return bookList[largestBook];	
	}

in Book :
Code:
	public int getNumPages ()
	{
		return numPages;
	}

Help is most appreciated.
 

ZKR

Honorable
Mar 12, 2012
35
0
10,580
I defined it that way:

Code:
public class Library
{
	private final int MAX_BOOKS = 150;
	private int totalBooks = 0;
	private int borrowedBooks;	
	private Book[] bookList;
	
	public Library ()
	{
		bookList = new Book[MAX_BOOKS];
		totalBooks = 0;
		borrowedBooks = 0;
	}
	
	public void addBook (String bookName, String authorName, int numPages)
	{
		if (totalBooks <= bookList.length)
		{
			bookList[totalBooks] = new Book (bookName, authorName, numPages);
			totalBooks++;
		}
		else 
			System.out.println ("Limit reached (150): Library is full.");
	}

What should I change?
 

randomizer

Distinguished
You could add a simple check inside the loop like this:

Code:
if (checkBook != null)
{
    do_something();
}

Your best option is to make sure that there are no null pointers. Just from the code I'm looking at here I can only assume that your Book constructor must return null somewhere. Never do this, or you'll have to put null checks everywhere. If you have to, just return a dummy instance. Your mostPagesBook() method should not have to concern itself with whether or not the Book is null.
 

ZKR

Honorable
Mar 12, 2012
35
0
10,580

Yes, I fixed that as you said. Thanks.
 

ZKR

Honorable
Mar 12, 2012
35
0
10,580
randoMIZER, I have changed it to use a simple arithmetical count (I`m not sure the null was introduced in the course):
Code:
public Book mostPagesBook ()
	{
		int pages, mostPages = 0, largestBook = 0;
		
		for (int check = 0; check < totalBooks; check++)
		{	
			if (bookList[check].isAvailable())
			{
				pages = bookList[check].getNumPages();
				if (pages > mostPages)
				{
					mostPages = pages;
					largestBook = check;	
				}
			}											
		}	
		return bookList[largestBook];	
	}