将对象传递给数组时遇到问题

时间:2014-07-01 20:06:02

标签: java arrays object null syntax-error

在下面的程序中,我在第41行(addNewItem方法的最后一行)和71(main方法的最后一行)获得java.lang.NullPointerException

import java.util.Arrays;
import java.util.Scanner;

public class TrippelTylerPersonalLendingLibrary {


    //Fields
    MediaItem[] items;
    int numberOfItems = 0;

    //Methods
    int displayMenu(){
        Scanner input = new Scanner(System.in);
        int choice;
        System.out.print("Menu\n" +
                "1. Add new item\n" +
                "2. Mark an item as on loan\n" +
                "3. List all items\n" +
                "4. Mark an item as returned\n" +
                "5. Quit\n\n" +
                "What would you like to do?");
        choice = input.nextInt();
        if(choice<1 || choice>5){
            while(choice<1 || choice>5){
                System.out.println("You have entered an invalid menu choice.\n" +
                        "What would you like to do?");
                choice = input.nextInt();
            }
            return choice;
        }
        else{
            return choice;
        }
    }

    void addNewItem(String title, String format){
        String titleNew = title;
        String formatNew = format;
        MediaItem newItem = new MediaItem(titleNew, formatNew);
        items[numberOfItems] = newItem;
    }

    void markItemOnLoan(String title, String name, String date){

    }

    String[] listAllItems(){

    }

    void markItemReturned(String title){

    }

    //Main method
    public static void main(String[] args) {

        TrippelTylerPersonalLendingLibrary instance = new TrippelTylerPersonalLendingLibrary();
        MediaItem instance2 = new MediaItem();

        //Fields for main method
        int choice;
        String newTitle;
        String newFormat;

        choice = instance.displayMenu();
        if(choice == 1){
            newTitle = instance2.setTitle();
            newFormat = instance2.setFormat();
            instance.addNewItem(newTitle, newFormat);
        }

    }

}

1 个答案:

答案 0 :(得分:0)

通常不应使用数组来存储未知数量的元素。

ArrayList效果更好,因为它可以按需膨胀:

 ArrayList<MediaItem> itemList = new ArrayList<MediaItem>();
 ...
 itemList.add(elem);

您可以随时从ArrayList中提取数组:

  T[] array = itemList.toArray(new T[itemList.size()]);

并且,如果您决定使用数组,请先将其初始化:

MediaItem[] items = new MediaItem[NUM_ELEM];

未能这样做是导致NullPointerException的原因。