【发布时间】:2014-11-03 19:46:48
【问题描述】:
我已经为此苦苦思索了一段时间......不知道该怎么办。
String tempprice = null;
String findPriceCommand = "SELECT sellingprice FROM `item` WHERE itemNo = '" + itemNo + "'";
try
{
tempprice = viewValue(conn, findPriceCommand);
}
catch (SQLException e)
{
e.printStackTrace();
}
Double price = Double.parseDouble(tempprice);
Double temp = (quantity.get(count) * price);
finalprice.add(temp);
我正在尝试使用 itemNo 从数据库中获取价格。由于我将此值作为字符串值获取,因此我使用Double price = Double.parseDouble(tempprice); 将其更改为双精度值。
在我将finalprice 变成ArrayList 之前,这一切都奏效了(这样我就可以一次插入多个值……(上面给出的代码是循环的一部分……)无论如何,现在我得到了NullPointerException
像这样:
int count = 0;
if (action.getSource() == btnAdd)
{
//other ArrayList variables
ArrayList<Integer> quantity = new ArrayList<Integer>();
ArrayList<Double> finalprice = new ArrayList<Double>();
//.....previous code...
count++;
}
知道我在这里缺少什么吗? :/
【问题讨论】:
-
tempprice 为空,这就是为什么你得到一个 NullPointerException
-
代码中的循环在哪里?
-
你需要开始使用调试器
-
根据documentation,您会在
Double.parseDouble(anything)上获得NPE 的原因只有一个——那就是anything是null。所以找出原因。你没有发布足够的信息让我们找到。您的堆栈跟踪会准确地告诉您错误在哪里,并且只有少数情况会导致 NPE。你错过的是对你的错误的基本分析和对可能原因的推断。 -
@ShifaTsar 另一种选择是正确设计您的程序。
tempprice是null的唯一方法是viewValue返回null或抛出异常。在这两种情况下,尽管viewValue失败,您为什么还要继续尝试解析它?如果viewValue在某些情况下应该返回null,您需要相应地处理它(例如if (tempprice == null))。适当地处理您的错误情况。
标签: java loops arraylist double