0

私は Java プロジェクトに取り組んでおり、現在 4 つのクラス (Driver、OrdersProcessor、Items、および Purchase) を持っています。テストを実行すると、(** * * の 2 行で NullPointerException があることがわかります。 *) それらの隣に。私は彼らの何が悪いのか分かりません..

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

}

}

そして他のクラス:

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;
}
4

2 に答える 2

1

最初のケースitemsでは値に設定されず、null のままのようです。
2 番目のケースでgetItem(name)は null が返されたため、呼び出しは.purchaseItem(id)失敗します。

簡単にデバッグするには、Eclipse にブレークポイントを設定する (または使用する) か、それらの行の前にいくつかのログ メッセージをコンソールに出力して、オブジェクトの現在の値を確認します。

于 2013-04-30T21:37:19.530 に答える
0

items は最初のクラスで null として定義されています。これをインスタンス化する必要があります。

2 番目の問題については、これを 1 行で行うことは避けてください。getItem() はおそらく null を返しています。これを 2 つの別個のステートメントに分割し、null チェックを追加します。コードセーフ、または開発者がメソッドから返されるもの (もしあれば) を保証するテスト。

于 2013-04-30T21:38:46.563 に答える