Exception in thread "main" java.lang.NullPointerException
Hi,
Im getting this error in my main class but not sure why. Hopefully someone can spot my error. The main class is:
Code:
public class BookMain{
public static void main(String[] args){
// Create Book
Book book = new Book("Data Structures");
// Create Chapters
Chapter ch1 = new Chapter();
Chapter ch2 = new Chapter();
Chapter ch3 = new Chapter();
Chapter ch4 = new Chapter();
ch1.setChapterTitle("Introduction");
ch2.setChapterTitle("Chapter 1");
ch3.setChapterTitle("Chapter 2");
ch4.setChapterTitle("Chapter 3");
// Create Pages
Page pg1 = new Page();
Page pg2 = new Page();
Page pg3 = new Page();
Page pg4 = new Page();
pg1.setPageNumber(1);
pg2.setPageNumber(2);
pg3.setPageNumber(3);
pg4.setPageNumber(4);
// errors occur here!
ch1.addPage(pg1);
ch2.addPage(pg2);
ch3.addPage(pg3);
ch4.addPage(pg4);
book.addChapter(ch1);
book.addChapter(ch2);
book.addChapter(ch3);
book.addChapter(ch4);
}
}
and the other classes which have instantiations within main look like this:
Code:
import java.util.ArrayList;
public class Book{
// Attributes
private ArrayList<Chapter> chapters;
String Title;
public Book(String ti){
Title = ti;
}
// Add chapter
public void addChapter(Chapter c){
chapters.add(c);
}
// Size of book in chapters
public void size(){
System.out.println("This book contains " +
chapters.size() + " chapters.");
}
//size of book in pages
public void numPages(){
int total = 0;
for(Chapter ch : chapters){
total += (int) ch.size();
}
System.out.println("the book has " + total + " pages.");
}
// Get Title
public void getTitle(){
System.out.println("Now reading: " + Title);
}
}
Code:
import java.util.ArrayList;
public class Chapter{
// Attributes
private ArrayList<Page> pages;
String chapterName;
// set chapter name
public void setChapterTitle(String ti){
chapterName = ti;
}
// get chapter name
public void getChapterTitle(){
System.out.println(" " + chapterName);
}
// Add page
public void addPage(Page p){
pages.add(p);
}
//How many pages
public int size(){
System.out.println("This chapter has " +
pages.size() + " pages.");
return pages.size();
}
}
Code:
public class Page{
// Attributes
int pageNumber;
// Set page Number
public void setPageNumber(int pgNum){
pageNumber = pgNum;
}
// Get page Number
public void getPageNumber(){
System.out.println("The page number is " + pageNumber);
}
}
The error occurs when I try add an object into another's inner ArrayList. E.g when I try add ch1 to book with book.addChapter(ch1);
Any ideas?
Cheers
BIOS
Re: Exception in thread "main" java.lang.NullPointerException
Re: Exception in thread "main" java.lang.NullPointerException
Hi DoWhile,
Thanks alot for the reply. Aha! That's great. I'm new to collections and this is basically an exercise in using them :P So i declared the ArrayList objects but didn't instantiate them! OOps. Will rectify.
Cheers
BIOS