Home  >  Forum  >  Core Java
Post New Query

Exception in thread "main" java.lang.NullPointerException


joined on
March 10,2015
Asked on March 11,2015
Wanna print the name of author and the title of the book.
BooksTestDrive.java
public class Books {
String title;
String author;
}

class BooksTestDrive{
public static void main(String[] args) {
Books[] myBooks = new Books[3];
int x = 0;
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;
}
}
joined on
March 10,2015
Replied on March 11,2015

You have to actually make the Books objects !
joined on
March 15,2013
Replied on March 11,2015

Create the  Books objects like..

myBooks[0] = new Books();
myBooks[1] = new Books();
myBooks[2] = new Books();

BooksTestDrive.java

public class Books {
String title;
String auther;
}

class BooksTestDrive{
public static void main(String[] args) {
Books[] myBooks = new Books[3];
int x = 0;
// Books object
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].auther = "bob";
myBooks[1].auther = "sue";
myBooks[2].auther = "ian";
while(x < 3){
System.out.print(myBooks[x].title);
System.out.print(" by ");
System.out.println(myBooks[x].auther);
x = x + 1;
}
}
}

Write Answer









Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us