1

The following code get's an error when compiled. I know it's missing something but I just can't figure out what.

public class Books {
    String title;
    String author;

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Books[] myBooks = new Books[3];

        myBooks[0].title = "Learn Java";
        myBooks[1].title = "Java Development";
        myBooks[2].title = "Java Today!";
        myBooks[0].author = "S";
        myBooks[1].author = "Mr. S";
        myBooks[2].author = "SN";

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

    }

}
some random dude
  • 419
  • 1
  • 3
  • 9

1 Answers1

0

Change

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

to

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

Consider case when x=2 at srat of the loop. It becomes 3 first and then books[3] will throw Exception.

Other than that you have simply defined an array which is nothing but just references. You need to initialize all of them.

for(Books book : myBooks ) {
   book = new Books();
}

If you are not initializing the array they are just pointing to null and if you perform any operations on it like myBooks[i].title you will get NPE.

Aniket Thakur
  • 58,991
  • 35
  • 252
  • 267