I have certain JSP code, wherein I can select multiple checkboxes and then I am supposed to add the values of the selected elements.
However, due to the elements being retrieved are in String format, I get a NumberFormatException
when I try to do this -
String chooseRight[] = request.getParameterValues("id");
if(chooseRight != null && chooseRight.length != 0){
int sum =0;
out.println("The sum is: ");
for (int i = 0; i < chooseRight.length; i++) {
sum += Integer.parseInt(chooseRight[i]);
out.println(sum);
}
}
How can I possibly display int
or float
value in out.print(sum);
?
Hi you can use typeof of to validate type in javascript such as
typeof "123"; // return string
typeof 123;// return number
typeof new Object(); // return object
Hope this info helped you out
Check out more about type checking in : http://www.avlabz.com/2013/01/geekyjs-javascript-strict-type-checking-plugin/
I don't think it's the out.println(sum);
that is the problem. sum
is declared as an int and will stay that way. The error must happen in Integer.parseInt()
, which in turn must be caused by chooseRight
containing strings that can't be parsed as integers.
See the docs for Integer.parseInt() , which state:
Throws: NumberFormatException - if the string does not contain a parsable integer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.