Problem with null pointer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AlarV
    New Member
    • Dec 2008
    • 37

    Problem with null pointer

    Hello everyone I'm new to java and this forum and I have a problem that I need to solve:

    I've created a program with a class and a main, which is this:


    CLASS BOOK:
    Code:
    public class Book {
        private String title;
        private String author;
        private int FirstEdition;
        public Book(){
        title="";
        author="";
        FirstEdition=0;
        };
        public void SetTitle(String a){
            this.title=a;
        }
        public void SetAuthor(String a){
            this.author=a;
        }      
        public void SetFirstEdition(int a){
            this.FirstEdition=a;
        }
        public String GetTitle(){
            return this.title;
        }
        public String GetAuthor(){
            return this.author;
        }
        public int GetFirstEdition(){
            return this.FirstEdition;
        }
        
    
    };

    MAIN:
    Code:
    public static void main(String[] args) {
            
            int i;
            Book [] a= new Book[2];        
            for(i=0;i<2;i++){
            a[i].SetTitle("1984");
            a[i].SetAuthor("Orwell");
            a[i].SetFirstEdition(1980);
            }
            for(i=0;i<2;i++){
                System.out.println("Book Title:"+a[i].GetTitle());
                System.out.println("\nAuthor Name:"+a[i].GetAuthor());
                System.out.println("\nFirst Edition:"+a[i].GetFirstEdition());
            }
            }

    I get this message:
    Exception in thread "main" java.lang.NullP ointerException
    at Askhsh4.Askhsh4 .main(Askhsh4.j ava:21)
    Java Result: 1


    Thanks everyone in advance!
  • JosAH
    Recognized Expert MVP
    • Mar 2007
    • 11453

    #2
    You have created an array that contains two Book references. Each of them can refer to (read: point to) a Book but they don't do that now (they are both equal to null as a matter of fact). Before you can do anything with one of your books you have to create them:

    Code:
    for (int i= 0; i < book.length; i++)
       book[i]= new Book();
    When that loop has finished both array elements each point to a book.

    kind regards,

    Jos

    Comment

    • AlarV
      New Member
      • Dec 2008
      • 37

      #3
      Oh my god, thank you so much my friend, I have been trying to figure out this since yesterday! :D :D

      Comment

      • Jibran
        New Member
        • Oct 2008
        • 30

        #4
        You only need one FOR loop there.

        Comment

        Working...