2016-10-02 18 views
-2

我正在处理一个范围问题,它将“数量无法解析为变量错误”。处理范围,数量无法解析为变量错误,使用try-catch块时如何解决问题

我知道它是什么意思,但我不知道如何解决它,给我的代码。

我正在处理数量和价格的BankAccount计划,这些必须是“双”类型。

我必须使用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"); 
      } 

    }} 

回答

0

你在除了你试图从访问一个较小的范围内定义quantity

前:

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

后:

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

当你离开的范围的水平,你的变量是 “留下” 的可能。

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

谢谢。这有诀窍,但我现在有一个不同的问题。 –