Dipan Garg
Dipan Garg

Reputation: 9

How to parse 10 digit phone number into Integer in Java

I have to do a validation where it is mentioned that phone number should be 10 digits like 9867610012 and if its true I have to set its value in a setter method whose argument is an Integer and I can't change it's argument. As we know, Integer has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). When I parse the String to Integer using Integer.parseInt("9867610012"), I am getting following exception at runtime:

Exception in thread "main" java.lang.NumberFormatException: For input string: "9867610012". 

Can you suggest some way where I can set a 10 digit String to Integer.

Thanks in Advance!!!!

Upvotes: 0

Views: 4363

Answers (2)

Mike B
Mike B

Reputation: 2784

As I commented, You should leave it as a String and then validate using regex.
In Your situation I'll give an example (10 digits, may start with zero). Don't assume that my code will be perfect - it's just to give you an idea.

boolean isValid = false;
do {
   Scanner phoneSc = new Scanner(System.in);
   String phone = phoneSc.next();
   isValid = isPhoneValid(phone);
} while (!isValid);


public boolean isPhoneValid(String phone) {
    String regex = "\\d{10}"; //regex for 10 digits
    return phone.matches(regex);
}

If You don't know regex, learn them. They are very useful. If You don't want to learn, web is full of examples. You can add to regex possible + in front, ( and ), maybe some dashes - cause some numbers have it. Regexes are perfect for such task.

Upvotes: 1

Kaushik NP
Kaushik NP

Reputation: 6779

Use parseLong().

public static long parseLong(String s) throws NumberFormatException

Parses the string argument as a signed decimal long. The characters in the string must all be decimal digits, except that the first character may be an ASCII minus sign '-' (\u002D') to indicate a negative value or an ASCII plus sign '+' ('\u002B') to indicate a positive value.

Parameters: s - a String containing the long representation to be parsed

Returns: the long represented by the argument in decimal.

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

And since Long.MAX_VALUE is 9,223,372,036,854,775,807, it can serve your purpose. So instead of Integer use Long.

Note to OP : as many have pointed out, you may need to review your code logic to consider various scenarios that you may come across later on. Do go through the comments once.

Upvotes: 0

Related Questions