Java NPE-帮助摆脱它



我目前得到以下代码:

captureFile = theCaptureFile;
    // If there is only 1 currency it gets the total right away
    if (captureFile.getTotalMoney().size() == 1) {
        Money totalMoney = captureFile.getTotalMoney().values().iterator().next();
        totalAmount  = totalMoney.getAmount();
        currencyCode = totalMoney.getCurrencyCode();
    }
    // If there is more than one currency, goes through every one, converts it to GBP and adds it to the total amount
    else if (captureFile.getTotalMoney().size() > 1) {
        Map<String, Money> totals = captureFile.getTotalMoney();
        for (Entry<String, Money> money : totals.entrySet()) {
            try {
                totalAmount = totalAmount + money.getValue().getEquivalent(BASE_CURRENCY).getAmount();
            } 
            catch (CurrencyNotFoundException e) {
                LOG.error("Getting ExchangeRate:", e);
                totalAmount = null;
                break;
            } 
            catch (ExchangeRateNotFoundException e) {
                LOG.error("Getting ExchangeRate:", e);
                totalAmount = null;
                break;
            }
        }
    }

当代码被调用时,第一个IF工作得很好,但如果有两种以上的货币,我会在TRY位上得到一个NullPointerException。这些方法都没有返回null,所以我猜我在映射部分提取值是错误的。

以下是其他2种方法:

public Money getEquivalent(String targetCurrencyCode) throws CurrencyNotFoundException,ExchangeRateNotFoundException {
    if (this.currencyCode.equals(targetCurrencyCode))   {
        return this;
    }
    return getEquivalent(CurrencyCache.get().getCurrency(targetCurrencyCode));
}

和:

public long getAmount() {
    return amount;
}

如有任何帮助,我们将不胜感激,您可能需要的更多信息请告诉我。

非常感谢。

由于totalAmount是可以为null的,并且它是在第一次迭代中使用的,因此需要在循环之前将其设置为非null值:

totalAmount = 0L;
Map<String, Money> totals = captureFile.getTotalMoney();
for (Entry<String, Money> money : totals.entrySet()) {
    try {
        totalAmount = totalAmount + money.getValue().getEquivalent(BASE_CURRENCY).getAmount();
    }
    ... 
}

如果在进入循环之前totalAmount未设置为null,则第一个+=调用将导致NPE。

您似乎在说这行抛出了一个NPE。

totalAmount = totalAmount +
         money.getValue().getEquivalent(BASE_CURRENCY).getAmount();

有4种方式可以实现:

  • 如果totalAmount被声明为Integer(或另一个基元包装器类型)并且它是null

  • 如果moneynull,则

  • 如果money.getValue()返回null

  • 如果CCD_ 13返回CCD_。

不幸的是,您的代码过于零碎,无法判断其中哪一个是可能的。

也有可能getEquivalent正在抛出NPE。。。不过这一点从堆叠比赛中可以清楚地看出。

事实上,这条线:

totalAmount = totalMoney.getAmount();

不抛出NPE不允许我们消除以上列出的任何可能性。

最新更新