java.lang.NullPointerException但我的对象不是';t空?

java.lang.NullPointerException但我的对象不是';t空?,java,Java,我调用inventory对象的所有方法都有这个问题。但是,对象不应该为null,因为我要求用户输入我存储在库存数组(对象数组)中的内容。我假设数据永远不会被存储,因为我在包含这个清单数组的所有方法中都有这个NPE。我相信我的方法代码是可以的 我看了类似问题的其他答案 我联系了我的导师 我多次检查我的代码 我在谷歌上搜索了我的问题,得到了与我的Java水平相当的复杂答案 这是我的密码 public class HouseHoldGoods { private static int

我调用inventory对象的所有方法都有这个问题。但是,对象不应该为null,因为我要求用户输入我存储在库存数组(对象数组)中的内容。我假设数据永远不会被存储,因为我在包含这个清单数组的所有方法中都有这个NPE。我相信我的方法代码是可以的

  • 我看了类似问题的其他答案
  • 我联系了我的导师
  • 我多次检查我的代码
  • 我在谷歌上搜索了我的问题,得到了与我的Java水平相当的复杂答案
这是我的密码

public class HouseHoldGoods {


    private static int numberOfGoods = 0; 
    private String type; 
    private String description;
    private int priceRiksdaler;
    private int priceSkilling; 
    private int priceRunstycken;

    //Constructor to initialize instance variables to 0 and null
    public HouseHoldGoods(){
        this.description = null;
        this.priceRiksdaler = 0;
        this.priceSkilling = 0;
        this.priceRunstycken = 0;
        numberOfGoods++;
    }

    //Constructor taking 3 arguments and initializes them to the given values.
    public HouseHoldGoods(String type, String description, OldSwedishCurrency currency){
        this.type = type;
        this.description = description;
        /*currency = new OldSwedishCurrency()*/;//NOT SURE OF THIS ONE
    }

    //Accessors
    public String getType(){
        return type; 
    }

    public String getDescription(){
        return description;
    }

    public int getPriceRiksdaler(){
        return priceRiksdaler; 
    }

    public int getPriceSkilling(){
        return priceSkilling; 
    }

    public int getPriceRunstycken(){
        return priceRunstycken;
    }

    public static int getNumberOfGoods(){
        return numberOfGoods;
    }

    //Mutators
    public void setType(String type){
        this.type = type;
    }

    public void setDescription(String description){
        this.description = description;
    }

    public void setPriceRiksdaler(int priceRiksdaler){
        this.priceRiksdaler = priceRiksdaler;
    }

    public void setPriceSkilling(int priceSkilling){
        this.priceSkilling = priceSkilling;
    }

    public void setPriceRunstycken(int priceRunstycken){
        this.priceRunstycken = priceRunstycken;
    }

    //Equals method checking if 2 objects are the same (same price, type and description)
    public boolean equals(HouseHoldGoods good){
        return(this.getType().equalsIgnoreCase(good.getType()) && this.getDescription().equalsIgnoreCase(good.getDescription()) && this.getPriceRiksdaler() == good.getPriceRiksdaler() && this.getPriceSkilling() == good.getPriceSkilling() && this.getPriceRunstycken() == good.getPriceRunstycken());
    }

    //To string method which will return the content of the object of type HouseHoldGoods with the appropriate labels

    public String toString(){
        return ("Description: " + description + "\n" + "Type: " + type + "\n" + "Price: " + priceRiksdaler + " riksdaler, " + priceSkilling + " skilling, " + priceRunstycken + " runstycken.");
    }   
}
司机

import java.util.Scanner; 
public class HouseHoldGoodsDriver {

    static Scanner keyboard = new Scanner(System.in);
    static final String PASSWORD = "comp249"; //Password 
    static String passwordInput = " "; //Password input by the user
    static int numItem = 0; //Number of items user wants to input in inventory
    public static HouseHoldGoods[] inventory;//Array that will store the number of items
    static int max = 5; //the maximum number of items that can be stored in inventory
    static int itemRemain = 0; //Remaining number of item that are possible to store in inventory

    public static void main(String[] args) {
        System.out.println("          ********** Welcome to Nancy's HouseHold goods store! **********");
        System.out.println();


        int choice = 0; //Choice Nancy will be making
        do{
        //Displaying the menu for Nancy to choose
        System.out.println("What would you like to do?");
        displayMenu();
        choice = keyboard.nextInt();
        System.out.println();

        //Declaring the inventory
        inventory = new HouseHoldGoods[max];

        switch (choice){
        //Option 1
        case 1:
            if(askPassword()){
                enterItem();
            }
            break;
        case 2:
            if(askPassword()){
                askUpdateItem();
            }
            break;
        case 3:
            itemOfType();
            break;
        case 4:
            itemPriceLowerThan();
            break;
        case 5:
            int choiceStats = 0; //choice selected by user in the statistics menu
            do{
            System.out.println("What information would you like to access?");
            displayStatsMenu();
            choiceStats = keyboard.nextInt();

            if(choiceStats == 1){
                System.out.println(inventory[cheapestItem()]);
                System.out.println("Item #" + (cheapestItem() + 1) + " is the cheapest.");
            }
            else if(choiceStats == 2){
                System.out.println(inventory[mostCostlyItem()]);
                System.out.println("Item #" + (mostCostlyItem() + 1) + " is the most costly.");

            }
            else if(choiceStats == 3){
                itemOfType();
            }
            else if (choiceStats == 4){
                averageCost();
            }
            //Handling the case where the input of the user does not appear in the stats menu
            while(choiceStats != 1 && choiceStats != 2 && choiceStats !=3 && choiceStats != 4 && choice != 5){
                displayStatsMenu();
                choiceStats = keyboard.nextInt();
            }
            //When user inputs 5, we quit the stats menu and display the main menu
            }while(choiceStats != 5);

        case 6:
            System.out.println("Come back soon!");
            System.exit(0); 
        }
        }
        while(choice!=6);
    }

    //A method that will display the menu 
        public static void displayMenu() {

            System.out.println("    1. Enter a new item in inventory (password required)");
            System.out.println("    2. Change information of an item in inventory (password required)");
            System.out.println("    3. Display all items of a specific type");
            System.out.println("    4. Display all items under a certain price");
            System.out.println("    5. Statistics on your inventory");
            System.out.println("    6. Quit");
            System.out.println("Please enter your choice >");
        }

        // Asking for password
        public static boolean askPassword() {
            int count = 0;
            //Asking the password at least once
            do {
                System.out.println("Please enter your password");
                passwordInput = keyboard.next();
                if (passwordInput.equals(PASSWORD))
                    return (passwordInput.equals(PASSWORD));
                count++; //Keeping track of the number of times it loops
            } while (!passwordInput.equals(PASSWORD) && count < 3);//When the count is greater than 3 and password is wrong, stop looping

            return false;
        }

        //Method to store items in the inventory
        public static void enterItem() {
            System.out.println("How many items would you like to enter?");
            numItem = keyboard.nextInt();
            itemRemain = max - HouseHoldGoods.getNumberOfGoods();
            int numOfItems = 0;
            /* If the user inputs a number of item bigger than the remaining
            number of items possible*/
            if (numItem > itemRemain) {

                numOfItems = itemRemain - HouseHoldGoods.getNumberOfGoods();
                System.out.println("You only have enough space for " + itemRemain + " item(s).");

                for (int i = HouseHoldGoods.getNumberOfGoods(); i < max; i++) {
                    inventory[i] = createItem();
                }

            }

            else {
                numOfItems = HouseHoldGoods.getNumberOfGoods() + numItem;
                for (int i = HouseHoldGoods.getNumberOfGoods(); i < numOfItems; i++) {
                    inventory[i] = createItem();
                }
            }
        }

        // Creating the items
        public static HouseHoldGoods createItem() {

            HouseHoldGoods good = new HouseHoldGoods();

            System.out.println("Please enter the description of the item");
            good.setDescription(keyboard.next());
            System.out.println("Please enter the type of the item");
            good.setType(keyboard.next());
            System.out.println("Please enter the price (riksdaler, skilling, runstycken)"); 
            good.setPriceRiksdaler(keyboard.nextInt());
            good.setPriceSkilling(keyboard.nextInt());
            good.setPriceRunstycken(keyboard.nextInt());

            return good;
        }

        //Method to update an item
        public static void askUpdateItem() {
            String answerToUpdate = " ";
            int itemNumber = 0;
            int updateChoice = 0;
            String answer = " ";

            do {

                System.out.println("Enter the number of the item you would like to update.");
                itemNumber = keyboard.nextInt();

                if (inventory[itemNumber - 1] == null) {
                    System.out.println("There is no item at this specific number.");

                    System.out.println("Would you like to enter another number? (yes/no)");
                    answer = keyboard.next();

                    if (answer.equalsIgnoreCase("yes")) {
                        askUpdateItem();
                    }
                    if (answer.equalsIgnoreCase("no")) {
                        displayMenu();
                    }
                } else {
                    System.out.println("Item #" + itemNumber);
                    System.out.println(inventory[itemNumber - 1]);
                    do {
                        displayUpdateMenu();
                        updateChoice = keyboard.nextInt();

                        if (updateChoice == 1) {
                            System.out.println("Enter the new type");
                            inventory[itemNumber - 1].setType(keyboard.next());
                        } else if (updateChoice == 2) {
                            System.out.println("Enter the new description");
                            inventory[itemNumber - 1].setDescription(keyboard.next());
                        } else if (updateChoice == 3) {
                            System.out.println("Enter the new price (riksdaler, skilling, ");
                            inventory[itemNumber - 1].setPriceRiksdaler(keyboard.nextInt());
                            inventory[itemNumber - 1].setPriceSkilling(keyboard.nextInt());
                            inventory[itemNumber - 1].setPriceRunstycken(keyboard.nextInt());
                        }

                        // While loop to handle the case where the user inputs a
                        // number that is not within the choice
                        while (updateChoice != 1 && updateChoice != 2 && updateChoice != 3){
                            displayUpdateMenu();
                            updateChoice = keyboard.nextInt();

                        }
                    } while (updateChoice != 4);
                }

                System.out.println("Do you want to update another Item?(yes/no)"); 

                answerToUpdate = keyboard.next();

            } while (answerToUpdate.equalsIgnoreCase("yes"));
        }

        // Display menu to update item
        public static void displayUpdateMenu() {
            System.out.println("What would you like to update?");
            System.out.println("  1. Type " + "\n" + "  2. Description" + "\n" + "  3. Price"
                    + "\n" + "  4. Quit");
        }


        //Method to display any item of a certain type
        public static void itemOfType(){ /*******THIS DOESNT WORK*/
            System.out.println("Please enter the type of the item(s) you would like to display.");
            String typeInput = keyboard.next();

            int count = 0; //To keep track of the number of item of the specific type
            for(int i = 0; i < HouseHoldGoods.getNumberOfGoods(); i++){
                if(inventory[i].getType().equalsIgnoreCase(typeInput)){
                    System.out.println("Item #" + (i+1));
                    System.out.println(inventory[i]);
                    count++;
                }
                System.out.println("There are " + count + " items of type " + typeInput + ".");
            }
        }

        //Method to display item of specific price
        public static void itemOfPrice(){

            System.out.println("Please enter the price of the item(s) you would like to display. (riksdaler, skilling, runstycken)");
            int riksdalerInput = keyboard.nextInt();
            int skillingInput = keyboard.nextInt();
            int runstyckenInput = keyboard.nextInt(); 

            int count = 0; 
            for(int i = 0; i < HouseHoldGoods.getNumberOfGoods(); i++){
                if(inventory[i].getPriceRiksdaler() == riksdalerInput && inventory[i].getPriceSkilling() == skillingInput && inventory[i].getPriceRunstycken() == runstyckenInput){
                    System.out.println("Iten #" + (i+1));
                    System.out.println(inventory[i]);
                    count++;
                }   
                System.out.println("There are " + count + " items of price " + riksdalerInput + " riksdaler, " + skillingInput + " skilling, " + runstyckenInput + " runstycken.");
            }
        }

        //Method to display the items with a lower price than the entered item
        public static void itemPriceLowerThan(){
            System.out.println("Please enter the price you would like to compare your items to. (riksdaler, skilling, runstycken");
            int priceInputRiksdaler = 0;
            int priceInputSkilling = 0;
            int priceInputRunstycken = 0; 
            priceInputRiksdaler = keyboard.nextInt();
            priceInputSkilling = keyboard.nextInt();
            priceInputRunstycken = keyboard.nextInt();

            for(int i = 0; i < inventory.length; i++){
                if(inventory[i].getPriceRiksdaler() < priceInputRiksdaler && inventory[i].getPriceSkilling() < priceInputSkilling && inventory[i].getPriceRunstycken() < priceInputRunstycken){ 
                    System.out.println("Item #" + (i+1));
                    System.out.println(inventory[i]);
                }
            }

        }

        //Method to display the statistics menu
        public static void displayStatsMenu() {
            System.out.println(
                    " 1. Cost and details of cheapest item " + "\n" + " 2. Cost and details of most costly iten" + "\n"
                            + " 3. Number of items of each type" + "\n" + " 4. Average cost of items in inventory"
                            + "\n" + " 5. Quit" + "\n" + "Enter your choice");

        }

        //Method to find the cheapest item
        public static int cheapestItem(){
        int lowestCostIndex = 0;
        for (int i = 0; i < HouseHoldGoods.getNumberOfGoods(); i++) {
            if (inventory[i].getPriceRiksdaler() < inventory[lowestCostIndex].getPriceRiksdaler() && inventory[i].getPriceSkilling() < inventory[lowestCostIndex].getPriceSkilling() && inventory[i].getPriceRunstycken() < inventory[lowestCostIndex].getPriceRunstycken())
                lowestCostIndex = i;
        }
        return (lowestCostIndex);
    }
    //Method to find the most costly item
        public static int mostCostlyItem(){
            int highestCostIndex = 0;
            for(int i = 0; i < HouseHoldGoods.getNumberOfGoods(); i++){
                if(inventory[i].getPriceRiksdaler() > inventory[highestCostIndex].getPriceRiksdaler() && inventory[i].getPriceSkilling() > inventory[highestCostIndex].getPriceSkilling() && inventory[i].getPriceRunstycken() > inventory[highestCostIndex].getPriceRunstycken())
                    highestCostIndex = i;
            }
            return(highestCostIndex);
        }

        //Method to calculate the average cost
        public static void averageCost(){
            int sumRiksdaler = 0; 
            int sumSkilling = 0; 
            int sumRunstycken = 0; 
            int averageRiksdaler = 0; 
            int averageSkilling = 0; 
            int averageRunstycken = 0; 

            for(int i = 0; i < inventory.length; i++){
                sumRiksdaler += inventory[i].getPriceRiksdaler();
                sumSkilling += inventory[i].getPriceSkilling();
                sumRunstycken += inventory[i].getPriceRunstycken();
            }
            averageRiksdaler = sumRiksdaler/HouseHoldGoods.getNumberOfGoods();
            averageSkilling = sumSkilling/HouseHoldGoods.getNumberOfGoods();
            averageRunstycken = sumRunstycken/HouseHoldGoods.getNumberOfGoods();
            System.out.println("The average cost is " + averageRiksdaler + " riksdaler, " + averageSkilling + " skilling, " + averageRunstycken + " runstycken");
        }



}
在“菜单”的每个循环中,您创建一个新实例
inventory=newhouseholdgoods[max]丢弃以前输入的所有内容,并让它充满
null
元素

int choice = 0; //Choice Nancy will be making
do {
    //Displaying the menu for Nancy to choose
    System.out.println("What would you like to do?");
    displayMenu();
    choice = keyboard.nextInt();
    System.out.println();

    // *** This be bad ***//
    //Declaring the inventory
    inventory = new HouseHoldGoods[max];

    switch (choice) {
        //Option 1
        case 1:
            if (askPassword()) {
                enterItem();
            }
            break;

将数组的创建移动到
do循环开始之前

那里有很多代码需要查看,但我对可能原因的第一直觉是,尽管您将库存声明为HouseHoldGoods数组,但您没有将库存[索引]声明为新的HouseHoldGoods()在尝试在householdGoodDriver.main(householdGoodDriver.java:41)的householdGoodDriver.itemOfType(householdGoodDriver.java:231)的线程“main”java.lang.NullPointerException中引用/分配它之前,我尝试在for循环中声明inventory[I]……它抛出了相同的异常,看起来代码比严格需要的代码还要多。您是否可以进一步减少代码,直到仍然遇到问题时无法删除任何代码?在调用
inventory[i]
上的方法之前,您需要将其初始化为
null
以外的值。
int choice = 0; //Choice Nancy will be making
do {
    //Displaying the menu for Nancy to choose
    System.out.println("What would you like to do?");
    displayMenu();
    choice = keyboard.nextInt();
    System.out.println();

    // *** This be bad ***//
    //Declaring the inventory
    inventory = new HouseHoldGoods[max];

    switch (choice) {
        //Option 1
        case 1:
            if (askPassword()) {
                enterItem();
            }
            break;