BIG_MAC_AND_FRIES BIG_MAC_AND_FRIES - 2 months ago 13
Java Question

Dealing with scope, uantity Cannot be Resolved to a variable Error, How to fix when using try-catch block

I am dealing with an issue of scope that is giving me the "Quantity cannot be resolved to a variable error."

I know what it means, but I don't know how to fix it, given my code.

I am working on a BankAccount program dealing with quantity and price, and these have to be of type "Double".

I have to use a try-catch block to catch an exception, but this is causing me to receive the error. I know that variables have to be declared before we can use them, however, under this context, I am not sure how to fix this issue.

Here is my code:

//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");
}

}}

Answer

You defined quantity in a smaller scope than where you're attempting to access it from.

Before:

try {
    Double quantity = /* some val */;
} catch () {...}
System.out.println(quantity); //Quantity wasn't defined earlier?

After:

Double quantity = 0D; //default value
try {
    quantity = /* some val */;
} catch () {...}
System.out.println(quantity); //Prints our value or some default

When you leave a level of scope, your variables are "left behind" as well.

String one = "1";
{
    String two = "2";
    {
        String three = "3";
        //I can read one, two, three
    }
    //I can read one, two
}
//I can read one