java处理作用域,uantity无法解析为变量错误,使用trycatch块时如何修复
我处理的是一个范围问题,它给了我“数量不能被解析为变量错误”
我知道这意味着什么,但考虑到我的代码,我不知道如何修复它
我正在做一个银行账户程序,处理数量和价格,这些必须是“双重”类型
我必须使用try-catch块来捕获异常,但这会导致我收到错误。我知道在使用变量之前必须声明变量,但是在这种情况下,我不确定如何解决这个问题
这是我的代码:
//Validate Quantity
nullpointerexception
try {
Double quantity = Double.parseDouble((request.getParameter("quantity")));
} catch (Exception e) {
hasError = true;
request.setAttribute("quantityError", true);
return;
}
//Validate Price
//Added after deadline to validate this entry and remove nullpointerexception
try{
Double price = Double.parseDouble((request.getParameter("price")));
} catch (Exception e) {
hasError = true;
request.setAttribute("priceError", true);
return;
}
// Redisplay the form if we have errors
if (hasError){
doGet(request, response);
return;
}
else{
// Cool, let's add a new description
List<InventoryEntry> entries = (List<InventoryEntry>) getServletContext().getAttribute("entries");
// Get a reference to the guest book
//List<GuestBookEntry> entries = (List<GuestBookEntry>) getServletContext().getAttribute("entries");
entries.add(new InventoryEntry(name, description, price, quantity));
response.sendRedirect("BankAccounts");
}
}}
# 1 楼答案
您在比试图从中访问
quantity
的范围更小的范围内定义了quantity
之前:
之后:
当你离开某个级别的作用域时,你的变量也被“甩在后面”