This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                4年前关闭。
            
                    
我目前有以下代码:

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。
这些方法都没有返回空值,因此我猜我在映射部分将值拉出是错误的。

以下是其他两种方法:

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值:

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。

10-08 06:49