NumberFormatexception for input string 999999999 - java

this is my html code
<div class="form-group col-md-6">
<input type="text" class="form-control" name="phonenumber" placeholder="Enter Phone Number">
</div>
this is my controller
int phonenumber=Integer.parseInt(request.getParameter("phonenumber").trim());
I am gettting error of NumberFormatException for input string '9999999999'
How to solve it.
Even though it is a number why cannot I parse it?

9999999999 is outside the valid range of values for the int data type (-231 to 231-1, inclusive), as specified by the Integer.MIN_VALUE and Integer.MAX_VALUE constants.
You cannot represent a full phone number in an int, you would have to omit the prefix and area code (0000000 - 9999999). Otherwise, use a long instead (-263 to 263-1, inclusive), Long.parseLong() will happily handle 9999999999.

The Exception because you are trying to convert '9999999999' into an Integer, and the max range of type int is 2147483647.
So try Long.parseLong("9999999999") instead if you are insisting on converting phone number from String into numbers. Storing and manipulating phone numbers as int or long will result in some inconsistencies in the future.
If you are doing that to check whether all the input characters are digits or not, you can use other ways such as using Regular Expressions. This way is very helpful since you can check formats, separator, etc. See this sample from MKyoung site:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ValidatePhoneNumber {
public static void main(String[] argv) {
String sPhoneNumber = "605-8889999";
//String sPhoneNumber = "605-88899991";
//String sPhoneNumber = "605-888999A";
Pattern pattern = Pattern.compile("\\d{3}-\\d{7}");
Matcher matcher = pattern.matcher(sPhoneNumber);
if (matcher.matches()) {
System.out.println("Phone Number Valid");
}
else
{
System.out.println("Phone Number must be in the form XXX-XXXXXXX");
}
}
}
And another simple way is to have a method which checks all the digits of a phone number are really digits:
public boolean isAllCharactersDigit(String phoneNumber){
for(char c: phoneNumber.toCharArray()){
if(!Character.isDigit(c))
return false;
}
return true;
}
Good Luck.

The range of an int in Java is -2,147,483,648 to 2,147,483,647.
9,999,999,999 is out of range and that is what is causing the exception.

Check parseInt() method in Oracles doc
parseInt
It clearly says
An exception of type NumberFormatException is thrown if any of the following situations occurs:
The first argument is null or is a string of length zero. The radix is
either smaller than Character.MIN_RADIX or larger than
Character.MAX_RADIX.
Any character of the string is not a digit of the specified radix,
except that the first character may be a minus sign '-' ('\u002D') or
plus sign '+' ('\u002B') provided that the string is longer than
length 1. The value represented by the string is not a value of type
int.
Examples:
parseInt("0", 10) returns 0
parseInt("473", 10) returns 473
parseInt("+42", 10) returns 42
parseInt("-0", 10) returns 0
parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
parseInt("2147483647", 10) returns 2147483647
parseInt("-2147483648", 10) returns -2147483648
parseInt("2147483648", 10) throws a NumberFormatException
parseInt("99", 8) throws a NumberFormatException
parseInt("Kona", 10) throws a NumberFormatException
parseInt("Kona", 27) returns 411787

Related

Why does the java accepts integer with a '+' sign and how to not accept integer input with a '+' sign

Why does the java accepts integer with a '+' sign and how to not accept integer input with a '+' sign. Please help! Thanks in advance
nAmount= scan.nextInt();
String sAmount = Integer.toString(nAmount);
//ON THIS LINE, MY PROG SHOULD NOT ACCEPT INTEGERS WITH "+" SIGN
if (sAmount.contains("+")) {
System.out.println("金額に文字が入力されています。");
} else if (nAmount<=0) {
System.out.println("金額は0円以上で入力してください。");
} else if (nAmount>999999) {
System.out.println("金額は999,999円以下で入力してください。");
} else nAFlag =1;
Sample Output :
Input > 100 (Accepted)
Input > -100 (Not Accepted because of the constrain input is less than 0)
Input > +100 (IT SHOULD NOT BE ACCEPTED BECAUSE IT CONTAINS A SYMBOL)
You are reading an int using Scanner.nextInt(): as described in the documentation, this uses Integer.parseInt to read the number; and that method explicitly states that it accepts a leading + sign:
The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), 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
And once you've read that number, there's no way to distinguish the fact that you entered 123 or +123, because there's no difference in the value. So, you've lost the + even before you convert the int to a String.
To capture this, you need to read the String first, and convert that to an int:
String sAmount= scan.next();
nAmount = Integer.parseInt(sAmount);
This preserves the + sign in sAmount, because there is no reason to strip it away. Note that it will fail if sAmount can't actually be parsed as an int.

Converting Hex in Java, wrong value with negative values

I have seen several questions on the topic mentioned in the subject (e.g this one), but it seems to me that none of them provided this example. I'm using Java7 and I want to convert a String representing an hexadecimal or a decimal into an Integer or Long value (depends on what it represents) and I do the following:
public Number getIntegerOrLong(String num) {
try {
return Integer.decode(num);
} catch (NumberFormatException nf1) {
final long decodedLong = Long.decode(num);
if ((int) decodedLong == decodedLong) {//used in Java8 java.util.Math.toIntExact()
return (int) decodedLong;
}
return decodedLong;
}
}
When I use a String representing a decimal number everything is ok, the problem are arising with negative hexadecimals
Now, If I do:
String hex = "0x"+Integer.toHexString(Integer.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Integer):
fails, because it returns a Long. Same for other negative integer values.
Moreover, when I use Long.MIN_VALUE like in the following:
String hex = "0x"+Integer.toHexString(Long.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Long):
fails, because of NumberFormatException with message:
java.lang.NumberFormatException: For input string: "8000000000000000"
I also tried with other random Long values (so within the Long.MIN_VALUE and Long.MAX_VALUE, and it fails as well when I have negative numbers. E.g.
the String with the hexadecimal 0xc0f1a47ba0c04d89 for the Long number -4,543,669,698,155,229,815 returns:
java.lang.NumberFormatException: For input string: "c0f1a47ba0c04d89"
How can I fix the script to obtain the desired behavior?
Long.decode and Integer.decode do not accept complemented values such as returned by Integer.toHexString : the sign should be represented as a leading - as described by the DecodableString grammars found in the javadoc.
The sequence of characters following an optional sign and/or radix specifier ("0x", "0X", "#", or leading zero) is parsed as by the Long.parseLong method with the indicated radix (10, 16, or 8). This sequence of characters must represent a positive value or a NumberFormatException will be thrown. The result is negated if first character of the specified String is the minus sign
If you can change the format of your input String, then produce it with Integer.toString(value, 16) rather than Integer.toHexString(value).
If you can switch to Java 8, use parseUnsignedInt/Long.

Java - Construct a signed numeric String and convert it to an integer

Can I somehow prepend a minus sign to a numeric String and convert it into an int?
In example:
If I have 2 Strings :
String x="-";
String y="2";
how can i get them converted to an Int which value is -2?
You will first have to concatenate both Strings since - is not a valid integer character an sich. It is however acceptable when it's used together with an integer value to denote a negative value.
Therefore this will print -2 the way you want it:
String x = "-";
String y = "2";
int i = Integer.parseInt(x + y);
System.out.println(i);
Note that the x + y is used to concatenate 2 Strings and not an arithmetic operation.
Integer.valueOf("-") will throw a NumberFormatException because "-" by itself isn't a number. If you did "-1", however, you would receive the expected value of -1.
If you're trying to get a character code, use the following:
(int) "-".charAt(0);
charAt() returns a char value at a specific index, which is a two-byte unicode value that is, for all intensive purposes, an integer.

Hex to binary conversion java

I have the following code
temp = "0x00"
String binAddr = Integer.toBinaryString(Integer.parseInt(temp, 16));
Why do I get the following error:
Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: For input string: "0x00"
Since the string contains 0x, use Integer.decode(String nm):
String binAddr = Integer.toBinaryString(Integer.decode(temp));
Because the leading 0x is not part of a valid base-16 number -- it's just a convention to indicate to a reader that a number is in hex.
Get rid of the '0x': from the javadocs:
The characters in the string must all be digits of the specified radix (as determined by whether Character.digit(char, int) returns a nonnegative value), 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. The resulting integer value is returned.
BigInteger.toString(radix) will solve this issue
Refer method description
Hope it helps.
The 0x is for integer literals, eg:
int num = 0xCAFEBABE;
but is not a parseable format. Try this:
temp = "ABFAB"; // without the "0x"
String binAddr = Integer.toBinaryString(Integer.parseInt(temp, 16));

ParseInt NumberFormatException on phone number

I'm getting the following error when trying to parse the phone number, "5554567899"
java.lang.NumberFormatException: For input string: "5554567899"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:495)
at java.lang.Integer.parseInt(Integer.java:527)
...
Obviously, the phone number is able to be parsed. I even referenced this question, and the byte code result was
53,53,53,52,53,54,55,56,57,57,
So there's no invisible characters in the string. I'm stumped, can anyone help?
Here's the section of the code that's throwing the error, for reference:
String fullNumber = null;
for(Phone phone : party.getPhones()) {
if(phone != null && !phone.getDialNumber().isEmpty()) {
if(!phone.getAreaCode().isEmpty()) {
fullNumber = phone.getAreaCode();
}
fullNumber += phone.getDialNumber();
if(phone1 == null || phone1.equals(0)) {
LOGGER.debug(displayCharValues(fullNumber));
phone1 = Integer.parseInt(fullNumber);
}
}
phone1 is of Java.lang.Integer type.
The value exceeds the int range. Parse it into a long variable.
Simple test:
int i = 5554567899;
is a compile time error: "The literal 5554567899 of type int is out of range"
Really a phone number shouldn't be treated as a number at all, but as a string or possibly as a datatype that you define yourself, breaking out the country code, area code, exchange, etc.
If you want to validate that it contains only numbers or numbers plus some of the standard phone-number separators, this can be done by regular expressions.
We call it a phone number, and it is a numeric string, but as the usage isn't for numeric computation, you're better off never trying to treat it as a number.
The same goes for "social security numbers".
5554567899 as a number is too big to fit in an int. Try Long.parseLong instead.
5554567899 exceeds Integer.MAX_VALUE (2147483647). Use Long or BigInteger instead:
BigInteger bigNumber = new BigInteger("5554567899");

Categories

Resources