-2

I have this problem with all my methods where I am calling inventory object. However, the object is not supposed to be null because I am asking the user for input which I store in the inventory array (an array of objects). I am assuming the data never gets stored since I have this NPE in all methods that contain this inventory array. I believe my code for the methods are ok.

  • I looked other answers on similar questions
  • I contacted my tutor
  • I reviewed my code multiple times
  • I googled my question and obtained over complicated answers for my level in Java.

Here is my code

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.");
    }   
}

DRIVER

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");
        }



}

Exception:

Exception in thread "main" java.lang.NullPointerException 
at HouseHoldGoodsDriver.itemOfType(HouseHoldGoodsDriver.java:231) 
at HouseHoldGoodsDriver.main(HouseHoldGoodsDriver.java:41) 
PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • 1
    There's a lot of code there to look through, but my first instinct for a possible cause is that although you're declaring inventory as an array of HouseHoldGoods, you're not declaring inventory[index] as a new HouseHoldGoods() before trying to reference/assign it. – John Clifford Jan 15 '16 at 00:07
  • Exception in thread "main" java.lang.NullPointerException at HouseHoldGoodsDriver.itemOfType(HouseHoldGoodsDriver.java:231) at HouseHoldGoodsDriver.main(HouseHoldGoodsDriver.java:41) – Jasmine Latendresse Jan 15 '16 at 00:07
  • I did try to declare inventory[i] in my for loop...it threw the same exception – Jasmine Latendresse Jan 15 '16 at 00:08
  • 1
    That looks like more code than strictly needed. Can you reduce the code further until no code can be removed while still running into the problem? – Panda Jan 15 '16 at 00:12
  • Before you can call a method on `inventory[i]` you need to initialize it to something other than `null`. – PM 77-1 Jan 15 '16 at 00:12
  • Please read "[How to create a **Minimal**, Complete, and Verifiable example](http://stackoverflow.com/help/mcve)". – Andreas Jan 15 '16 at 00:18

1 Answers1

1

On each loop of your "menu", you create a new instance of inventory = new HouseHoldGoods[max]; throwing away everything that was previous entered into it and leaving it full of null elements

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;

Move the creation of the array to before the do-loop starts

duffymo
  • 305,152
  • 44
  • 369
  • 561
MadProgrammer
  • 343,457
  • 22
  • 230
  • 366