"Exception in thread "main" java.lang.NullPointerException" -


i'm trying run program will, if goes well, able take year , return title of album released in year. i've given 6 albums , i'm trying print title. i've fixed few pretty frustrating errors, 1 i've not seen before. error appears @ line 21, i'm not sure means. can help?

package songselector;  import java.util.scanner;  public class main {     public class album     { int year; string title; public album () { this.year = 0; this.title = null;         } public album (int year, string title) { this.year = year; this.title = title;      }     }     class cake { album[] albums; public cake () { albums = new album[6]; albums[0].year = 1994; albums[0].title = "motorcade of generosity"; albums[1].year = 1996; albums[1].title = "fashion nugget"; albums[2].year = 1998; albums[2].title = "prolonging magic"; albums[3].year = 2001; albums[3].title = "comfort eagle"; albums[4].year = 2004; albums[4].title = "pressure chief"; albums[5].year = 2011; albums[5].title = "showroom of compassion";      }  public void printalbum (int y) { system.out.println (albums[y].title);     }      }      public static void main(string[] args) {         new main().new cake().printalbum (0);     } } 

it means trying access / call method on object null. in case, initialized array of albums, didn't initialize each of albums in array.

you need initialize each album in array:

albums = new album[6]; albums[0] = new album(); albums[0].year = 1994;  albums[0].title = "motorcade of generosity"; ... 

or simpler (as @entonio pointed out):

albums = new album[6]; albums[0] = new album(1994, "motorcade of generosity"); albums[1] = new album(1996, "fashion nugget"); ... 

since have proper constructor.

one more thing: don't call more 1 method in each line, debugging.


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -