0

I know ths is a common question here. I have read the solutions and modified the code then also i am not getting the solution so I have posted my code here.

when I read a value from the text box and parse the value into int from String in servlet, why does it show NumberFormatException?

  String ph=request.getParameter("phone");
  int phone=Integer.parseInt(ph.trim());// exception is generated here
1
  • What's the value you are feeding it? Commented Jan 29, 2013 at 20:36

3 Answers 3

2

You can't have any characters or symbols in an int AND the maximum size of an int is 2,147,483,647 which means the phone number 555 555 5555 would be to large to store in an int.

Change the parse to a long and it should fix your problem

A good rule to follow is do not store any number like SSN or Phone numbers's in numerical primitives. You want to leave the numerical primitives for values you plan on doing something math related. Keep them as strings if at all possible.

Sign up to request clarification or add additional context in comments.

Comments

1

Because the value you are feeding it is not a valid integer. Make sure it doesn't have strange characters in it.

9835008199 is higher then MAXINT, so that's probaly it.

The docs tell me:

Throws NumberFormatException - if the string does not contain a parsable integer.

On another note: do not store phone numbers as integers. You will get in trouble (you are in fact already). Rule of thumb: if you do not want to do math with a number, it's not an int, but a string.

1 Comment

its a valid number 9835008199
0

Use isNumber function to check whether it is a valid number.

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.