CCC
CCC

Reputation: 15

Java Null Pointer Exception

I'm working on a Java project, and currently have 4 classes (Driver, OrdersProcessor, Items, and Purchase) and when I run the tests, it is telling me that I have a NullPointerException at the two lines with (** * **) next to them. I'm not sure what's wrong with them though..

public class OrdersProcessor {

private static Items items = null;

//added
    items = new Items(numOrders);

public static void runOrderProcessor(BufferedReader file, int id) {
    double grandTotal = 0;
    int clientId = 1000 + id;
    try {
        System.out.println("Reading order for client with id: " + clientId);
        file.readLine();
        while (true) {
            grandTotal += items.buy(file.readLine().split(" ")[0], id); (*****)
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        file.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    StringBuffer writeReport = new StringBuffer();
    writeReport.append("----- Order details for client with Id: "
            + clientId + " -----" + "\n");
    for (String bought : items.allItems()) {
        writeReport.append("Item's Name: " + items.getItem(bought)
                + items.getItem(bought).recipt(id));
        writeReport.append("Order Total: "
                + NumberFormat.getCurrencyInstance().format(grandTotal)
                + "\n");
    }

}

}

And the other class:

public class Items {

private Map<String, Purchase> items;
private double grandTotal;
private int numOrders;

public Items(int numOrders) {
    this.numOrders = numOrders;
    reportOrders = new TreeMap <Integer, String>();
    items = new TreeMap<String, Purchase>();
    grandTotal = 0;

public double buy(String name, int id) {
    double price = getItem(name).purchaseItem(id); (*****)
    synchronized (lockGT) {
        grandTotal = grandTotal + price;
    }
    return price;
}

Upvotes: 0

Views: 634

Answers (2)

clicky
clicky

Reputation: 865

items is defined as null in the first class. You need to instantiate this.

For the second issue, you should avoid doing this in one line. getItem() is probably returning null. Split it into two separate statements and add null checks. Code safe or to tests that ensure the developer what will be returned (if anything) from a method.

Upvotes: 0

Jean-Bernard Pellerin
Jean-Bernard Pellerin

Reputation: 12670

It looks like in the first case items is never set to a value and stays null.
In the second case getItem(name) has returned null so the call to .purchaseItem(id) fails.

To debug easily you can either set breakpoints in eclipse(or w.e you use) or print a few log messages to the console before those lines to see what the current values of the objects are.

Upvotes: 1

Related Questions