java 添加到 BigDecimal 时出现 NullPointerException

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9862219/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:40:54  来源:igfitidea点击:

NullPointerException when adding to BigDecimal

javanullpointerexception

提问by Dan

String[] toppings = new String[10];
BigDecimal toppingsPrice = null;

toppings[0] = req.getParameter("extraCheese");
toppings[1] = req.getParameter("moreTomatoes");
toppings[2] = req.getParameter("extraOnions");
// ...

for(int i = 0; i < toppings.length; i++) {
    if(toppings[i] != null) {
        toppingsPrice.add(new BigDecimal("0.99")); // <-- NPE is caused here.
        toppingsPrice = toppingsPrice.setScale(2, BigDecimal.ROUND_HALF_EVEN);
    }
}

I am getting a NullPointerExceptionin the above code when adding 0.99to toppingsPrice. I am working with money values, so I have used BigDecimal. Is there something wrong with how I am adding the 0.99c price?

我得到一个NullPointerException加时在上面的代码0.99toppingsPrice。我正在处理货币价值,所以我使用了BigDecimal. 我添加 0.99c 的价格有什么问题吗?

回答by Tudor

You are setting toppingsPriceto null and never changing it to point to something:

您将设置toppingsPrice为 null 并且永远不会将其更改为指向某些内容:

    BigDecimal toppingsPrice = null;
    ...
    toppingsPrice.add(new BigDecimal("0.99"));

Did you mean

你的意思是

BigDecimal toppingsPrice = new BigDecimal(0);

回答by gkamal

You need to initialize toppingsPrice

您需要初始化 toppingsPrice

change this line

改变这一行

BigDecimal toppingsPrice = null;

to

BigDecimal toppingsPrice = new BigDecimal(0);

回答by malina

If you would have a look at API you would see that :

如果您看一下 API,您会看到:

add(BigDecimal augend)

添加(BigDecimal 被加数)

Returns a BigDecimal whose value is (this + augend), and whose scale is max(this.scale(), augend.scale()).

返回一个 BigDecimal,其值为 (this + augend),其比例尺为 max(this.scale(), augend.scale())。