0
public class BooksTestDrive {
 public static void main(String[] args) {

  Books [] myBooks = new Books[3];
  int x=0;
  myBooks[0].title = "The Grapes of Jave";
  myBooks[1].title = "The Java Gatsby";
  myBooks[2].title = "The Java Cookbook";
  myBooks[0].author = "bob";
  myBooks[1].author = "sue";
  myBooks[2].author = "ian";

 while (x < 3) {
  System.out.print(myBooks[x].title);
  System.out.print("by");
  System.out.println(myBooks[x].author);
  x = x+1;
  }
 }
}

This code compiles but while runtime, its giving nullpointer exception.

2
  • 3
    Always indicate what line the exception was thrown in! For more complex problems include the complete stacktrace. Commented Jan 15, 2011 at 14:17
  • 1
    Exactly where does the exception is thrown ? Commented Jan 15, 2011 at 14:18

5 Answers 5

5

Your allocation of MyBooks[3] only assigns the array You still need to assign a "new MyBook()" to each entry in your array.

Sign up to request clarification or add additional context in comments.

Comments

2

look at your line:

Books [] myBooks = new Books[3];

you create an array, although every element in the array is a null pointer.

Comments

2

Saw it, you need to initializate each one of the elments of your array, try it with in an for or a while

Comments

1

This should work :

public class BooksTestDrive {
public static void main(String[] args) { 
      Books [] myBooks = new Books[3];
      // init loop
      for (int i=0;i<myBooks.length;i++) {
         myBooks[i] = new Books();
      }

      myBooks[0].title = "The Grapes of Jave";
      myBooks[1].title = "The Java Gatsby";
      myBooks[2].title = "The Java Cookbook";
      myBooks[0].author = "bob";
      myBooks[1].author = "sue";
      myBooks[2].author = "ian";

      for (Books book : myBooks) {
          System.out.printf("%s by %s\n",book.title,book.author);
      }
     }
}
}

Comments

0

You need to add the books to the arrays. This should work:

class BooksTestDrive {
    public static void main(String [] args) {
        Books [] myBooks = new Books[3];
        int x = 0;
        // THIS IS WHAT WAS MISSING.
        myBooks[0] = new Books();
        myBooks[1] = new Books();
        myBooks[2] = new Books();

        myBooks[0].title = "The Grapes of Java";
        myBooks[1].title = "The Java Gatsby";
        myBooks[2].title = "The Java Cookbook";
        myBooks[0].author = "bob";
        myBooks[1].author = "sue";
        myBooks[2].author = "ian";

        while (x < 3) {
            System.out.print(myBooks[x].title);
            System.out.print(" by ");
            System.out.println(myBooks[x].author) ;
            x = x + 1;
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.