I can compile just fine but when I try and run the program I get this message. Can someone please help me out with this. "Exception in thread "main" java.lang.NullPointer.Exception
class BooksTestDrive { public static void main(String[] args) { Books[] myBooks = new Books[3]; myBooks[0].title = "The Grapes of wrath"; myBooks[1].title = "The Java"; myBooks[2].title = "The Java cookbook"; myBooks[0].author = "bob"; myBooks[1].author = "joe"; myBooks[2].author = "deb"; int x = 0;
while (x < 2) { System.out.print(myBooks[x].title); System.out.print("by"); System.out.print(myBooks[x].author); x = x+1; } } }
Tony Morris
Ranch Hand
Joined: Sep 24, 2003
Posts: 1608
posted
0
Originally posted by Rick Rod: I can compile just fine but when I try and run the program I get this message. Can someone please help me out with this. "Exception in thread "main" java.lang.NullPointer.Exception
class BooksTestDrive { public static void main(String[] args) { Books[] myBooks = new Books[3]; myBooks[0].title = "The Grapes of wrath"; myBooks[1].title = "The Java"; myBooks[2].title = "The Java cookbook"; myBooks[0].author = "bob"; myBooks[1].author = "joe"; myBooks[2].author = "deb"; int x = 0;
while (x < 2) { System.out.print(myBooks[x].title); System.out.print("by"); System.out.print(myBooks[x].author); x = x+1; } } }
You stack trace will tell you more. Specifically, it will point to the line myBooks[0].title = "The Grapes of wrath"; You can use this stack trace to diagnose your issue using a systematic approach (no brain cells required). That approach is document here.
Look for a section
// An object reference referring to an object called 'o'. // All elements of the array are initialized to null. Object[] o = new Object[10]; // Dereferencing a null object reference (the fourth element of the array referred to by 'o'). String s = o[4].toString();
Thank you for your documentation it was a big help. I figured out that I had to refer the array's to the object and it worked.
on a side note how would I get the wording to be equally spaced out. right now the outcome is "the grapes of wrathbybobthe java byjoethe java cookbookbydeb" I want to have it as "the grapes of wrath by bob the java by joe the java cookbook by deb" Now you can really tell I am a begginer.
Rick Rod
Greenhorn
Joined: Nov 20, 2005
Posts: 10
posted
0
I figured it out, trial an error, it works if you just keep trying.
Steve Liem
Greenhorn
Joined: Dec 03, 2005
Posts: 17
posted
0
I would never use a while loop and guess about the length of myBooks!
for (int x = 0; x < myBooks.length; x++) { System.out.println(myBooks[x].title + " by " + myBooks[x].author); }