Java Question

Using, and parsing Doubles in request.getParameter("price"); Java Servlets

I have to use doubles/int to parse some data that is numeric in nature, but I want to test for null.

I am collecting the data using a request.getParameter() call for my servlet.

This is my code:

I currently have a ClassCast exception saying that a String cannot be cast to an Int/Double.

How do I get around this error?

int quantity = Integer.parseInt(request.getParameter("quantity") == null ? "" : Integer.parseInt(request.getParameter("quantity")));

Answer Source

You need to decide the business logic for dealing with possible null values in the quantity parameter. One sensible solution might be to assume that a missing or null value for quantity indicates that the quantity be zero:

String quantityStr = request.getParameter("quantity");
int quantity = 0;  // replace with whatever default value you want

// only parse for non-null, non-empty inputs
if (quantityStr != null && quantityStr.length() > 0) {
    quantity = Integer.parseInt(quantityStr);