0

I do not understand why I keep getting this null pointer exception, I do not know a lot about references and pointers and such and just started learning classes and objects. Help is much appreciated! Here is the code with the issue:

public class Library {

    public static MediaItem[] item = new MediaItem[100];

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        int choice = 0;
        int numberOfItems = 0;

        System.out.println("Personal Lending Library!");

        while (choice !=6) {

            choice = menu(input);

            switch(choice) {
            case 1: addNewItem(numberOfItems, input);
                break;
            case 2:
                break;
            case 3: listItems(numberOfItems);
                break;
            case 4:
                break;
            }

        }

    }

public static void addNewItem(int numberOfItems, Scanner input) {

         numberOfItems++;
         System.out.print("Enter the title: ");
         item[numberOfItems].title = input.nextLine();
         System.out.print("Enter the format: ");
         item[numberOfItems].format = input.nextLine();
Zach
  • 39
  • 2
  • Please post what the error says. For which variable – DanSchneiderNA Oct 21 '18 at 03:20
  • I think you didn't posted the full code. Please post the full code and also mention what error is being shown in the log. – Rashedur Rahman Oct 21 '18 at 03:24
  • 1
    It is probably this: `item[numberOfItems].title = ...`. As far as I can see, you have not initialized `item[numberOfItems]` with a reference to an `Item` object. So it will be `null`. So `null.title = ...` will throw an NPE. This is covered in the linked Q&A. Please read it / them. – Stephen C Oct 21 '18 at 03:28
  • 1
    In future, when you ask for help debugging code, please provide **all** of the evidence ... including the full stacktrace. If there is too much code, create an MCVE. – Stephen C Oct 21 '18 at 03:32
  • Thank you @StephenC Very helpful! And sorry this was a duplicate im a newbie on this site, and next time I will post all of my code – Zach Oct 21 '18 at 17:01

0 Answers0