0

I'm working with JavaEE i need to convert this: request.getParameter("id") to int. The value of request.getParameter("id") is "9" (String). When I'm trying to convert to int I have

java.lang.NumberFormatException

I've tried java.lang.Integer.parseInt(request.getParameter("id")) and request.getParameter("id",10) but it donsen't works...

Any solutions? Thank you.

5
  • 1
    are you sure id parameter is a number?try trimming the string Commented Apr 9, 2015 at 17:57
  • 1
    Is there any leading or trailing spaces? If there is, you would need to trim() it before calling parseInt() Commented Apr 9, 2015 at 17:57
  • 1
    Hidden characters? Try trimming the string: java.lang.Integer.parseInt(request.getParameter("id").trim()). If that doesnt work maybe try printing out the character codes in the string. Commented Apr 9, 2015 at 17:57
  • 3
    Incredible - At least three persons had the same idea at the same time - trim the string. Commented Apr 9, 2015 at 17:58
  • @VictorStafusa I'm wondering if OP failed to trim() the string. What do you think? Commented Apr 9, 2015 at 18:09

2 Answers 2

2

A complete full proof code would be

    String idString = request.getParameter("id");
    if(idString != null) {
        try {
            System.out.println(idString.trim()); // print to verify
            int idInt = Integer.parseInt(idString.trim());
        }
        catch(NumberFormatException nbe) {
            nbe.printStackTrace();
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

0

First you need to check whether String returned by getParameter() is null or not then check whether it is empty ("") String or not then use Integer.parseInt().

String id = request.getParameter("id");
    if(null != id && !("".equals(id))) {
        try {
            int number = Integer.parseInt(id.trim());
        }
        catch(NumberFormatException e) {
            e.printStackTrace();
        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.