java.lang.NumberFormatException: For input string: "9646324351" - java

public int reverse(int x) {
String xString=String.valueOf(Math.abs(x));
StringBuffer reverseX=new StringBuffer (xString);
if (x>=Integer.MIN_VALUE & x<=Integer.MAX_VALUE) {
reverseX=reverseX.reverse();
if (x<0)
reverseX=reverseX.insert(0,"-");
return Integer.parseInt(reverseX.toString());
}
else
return 0;
}
Runtime Error Message:
Line 12: java.lang.NumberFormatException: For input string:
"9646324351"
Last executed input:
1534236469
What's wrong? help plz Orz!!!

if you try to call your method with the value:
reverse(9646324351);
You get an Compiler error, which leads you to the Problem:
The literal 9646324351 of type int is out of range
So i do not understand why you can get an error in your method.
Use a long/Long or a BigInterger in your program
Here you can rad about the data types and which range they cover

That number is too large to be parsed as an Interger, it exceeds Integer.MAX_VALUE.
Rather use Long.parseLong

Use biginteger class instead of Integer
Read the docs https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html

public long reverse(int x) {
String xString=String.valueOf(Math.abs(x));
StringBuffer reverseX=new StringBuffer (xString);
if (x>=Integer.MIN_VALUE & x<=Integer.MAX_VALUE) {
reverseX=reverseX.reverse();
if (x<0)
reverseX=reverseX.insert(0,"-");
return Long.parseLong(reverseX.toString());
}
else
return 0L;
}
You can try above code.
As this 9646324351 value is out of range of int type.You need to provide larger datatype for this String to numeric conversion.
As we know
double's range > long's range >int's range
Also you can try BigInteger
Hope this will help you.

Related

If a String containing a number bigger than Integer.MAX_VALUE

I want to find if given String "99999999999999999999999999" or any massive number which would not fit in any datatype.I would like to find if that number is bigger than Integer.MAX_VALUE
Use BigInteger
BigInteger maxInt = BigInteger.valueOf(Integer.MAX_VALUE);
BigInteger value = new BigInteger("whatever");
if (value.compareTo(maxInt) > 0)
{
// larger
}
You could construct a BigInteger object from the string and then compare that BigInteger to Integer.MAX_VALUE.
You can call parseInt and catch NumberFormatException, which will be thrown if the number is too large (though it will also be thrown if the String has non-numeric characters).
If you want to avoid the exception, you can run the following checks:
If the String has more than 10 characters (or 11 if the first character is '-' or '+'), it must be larger than Integer.MAX_VALUE or smaller than Integer.MIN_VALUE.
Otherwise, call Long.parseLong() and compare the result to Integer.MAX_VALUE.
You can parse it as an int and catch an exception or BigInteger, or you can do a String comparison.
static final String MAX_INT_STR = Integer.toString(Integer.MAX_VALUE);
public static boolean checkInt(String s) {
return s.length() > MAX_INT_STR.length() || s.compareTo(MAX_INT_STR) > 0;
}
This could be used to avoid throwing some Exceptions before trying to parse it.
NOTE: This doesn't check that it only contains digits, but if it's a positive number it will check it is in bounds without parsing the string.
Try the following code to check if it's too big to fit inside an integer:
String num = "99999999999999999999999999";
try {
Integer.parseInt(num);
} catch(NumberFormatException ex) {
System.out.println("String did not fit in integer datatype");
}
This code will attempt to parse num into an integer, we can catch whenever that goes wrong and execute code when that happens (in this case a simple println).
From parseInt():
Throws: NumberFormatException - if the string does not contain a
parsable integer.

error while parsing an int from a char in String

import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(s, s.charAt(0)); // ERROR!
}
}
I want to parse the input string based on char position to get the positional integer.
Error message:
Exception in thread "main" java.lang.NumberFormatException: radix 49 greater than Character.MAX_RADIX
at java.lang.Integer.parseInt(Unknown Source)
at test.main(test.java:11)
That method you are calling parseInt(String, int) expects a radix; something that denotes the "number system" you want to work in, like
parseInt("10", 10)
(10 for decimal)! Instead, use
Integer.parseInt(i)
or
Integer.parseInt(i, 10)
assuming you want to work in the decimal system. And to explain your error message - lets have a look at what your code is actually doing. In essence, it calls:
Integer.parseInt("123", '1')
and that boils down to a call
Integer.parseInt("123", 49) // '1' --> int --> 49!
And there we go - as it nicely lines up with your error message; as 49 isn't a valid radix for parsing numbers.
But the real answer here: don't just blindly use some library method. Study its documentation, so you understand what it is doing; and what the parameters you are passing to it actually mean.
Thus, turn here and read what parseInt(String, int) is about!
Integer.parseInt(parameter) expects the parameter to be a String.
You could try Integer.parseInt(s.charAt(0) + ""). The +"" is to append the character to an empty String thereby casting the char to String and this is exactly what the method expects.
Another method to parse Characters to Integers (and in my opinion much better!) is to use Character.getNumericValue(s.charAt(0));
Check this post for further details on converting char to int
Need to convert String.valueOf(s.charAt(0)) to String.valueOf(s.charAt(0)) i.e. Char to String.
import java.util.*;
public class test
{
public static void main(String[] args)
{
int i = 123;
String s = Integer.toString(i);
int Test = Integer.parseInt(String.valueOf(s.charAt(0)));
}
}
Let use what we have here.
To parse one digit from a String into an integer. Use getNumericValue(char)
In your case, to get the first character into a number :
int n = Character.getNumericValue(s.charAt(0));
Be aware that you should take the absolute value if you integer can be negative.

CharSequence to Integer with multiple +ve and -ve signss

i have learned that to convert charsequence to integer we can use this statement
String cs="123";
int number = Integer.parseInt(cs.toString());
what if
cs = "++-+--25";
will this statement still run and give answer -25 according to string given??
You are end up with a NumberFormatException since ++-+--25 is not a valid integer.
See the docs of parseInt()
Parses the string argument as a signed decimal integer. 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. The resulting integer value is returned, exactly as if the argument and the radix 10 were given as arguments to the parseInt(java.lang.String, int) method.
So you are allowed to do
CharSequence cs = "-25"; //gives you -25
and
CharSequence cs = "+25"; //gives you 25
Otherwise ,take necessary steps to face the Exception :)
So know the char Sequence is a valid string just write a simple method to return true or false and then proceed further
public static boolean {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false; // no boss you entered a wrong format
}
return true; //valid integer
}
Then your code looks like
if(isInteger(cs.toString())){
int number = Integer.parseInt(cs.toString());
// proceed remaining
}else{
// No, Operation cannot be completed.Give proper input.
}
Answer to your question is code will run and throw Exception as "++-+--25" is not a valid int,
java.lang.NumberFormatException: For input string: "++-+--25"
You will get
java.lang.NumberFormatException: For input string: "++-+--25"
Tested example :
CharSequence cs = "++-+--25";
System.out.println("" + Integer.parseInt(cs.toString()));

java convert to int

I am trying to convert to int like this, but I am getting an exception.
String strHexNumber = "0x1";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
Exception in thread "main" java.lang.NumberFormatException: For input string: "0x1"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Integer.parseInt(Integer.java:458)
It would be a great help if someone can fix it.
Thanks.
That's because the 0x prefix is not allowed. It's only a Java language thing.
String strHexNumber = "F777";
int decimalNumber = Integer.parseInt(strHexNumber, 16);
System.out.println(decimalNumber);
If you want to parse strings with leading 0x then use the .decode methods available on Integer, Long etc.
int value = Integer.decode("0x12AF");
System.out.println(value);
Sure - you need to get rid of the "0x" part if you want to use parseInt:
int parsed = Integer.parseInt("100", 16);
System.out.println(parsed); // 256
If you know your value will start with "0x" you can just use:
String prefixStripped = hexNumber.substring(2);
Otherwise, just test for it:
number = number.startsWith("0x") ? number.substring(2) : number;
Note that you should think about how negative numbers will be represented too.
EDIT: Adam's solution using decode will certainly work, but if you already know the radix then IMO it's clearer to state it explicitly than to have it inferred - particularly if it would surprise people for "035" to be treated as octal, for example. Each method is appropriate at different times, of course, so it's worth knowing about both. Pick whichever one handles your particular situation most cleanly and clearly.
Integer.parseInt can only parse strings that are formatted to look just like an int. So you can parse "0" or "12343" or "-56" but not "0x1".
You need to strip off the 0x from the front of the string before you ask the Integer class to parse it. The parseInt method expects the string passed in to be only numbers/letters of the specified radix.
try using this code here:-
import java.io.*;
import java.lang.*;
public class HexaToInteger{
public static void main(String[] args) throws IOException{
BufferedReader read =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexadecimal value:!");
String s = read.readLine();
int i = Integer.valueOf(s, 16).intValue();
System.out.println("Integer:=" + i);
}
}
Yeah, Integer is still expecting some kind of String of numbers. that x is really going to mess things up.
Depending on the size of the hex, you may need to use a BigInteger (you can probably skip the "L" check and trim in yours ;-) ):
// Convert HEX to decimal
if (category.startsWith("0X") && category.endsWith("L")) {
category = new BigInteger(category.substring(2, category.length() - 1), 16).toString();
} else if (category.startsWith("0X")) {
category = new BigInteger(category.substring(2, category.length()), 16).toString();
}

java: Long.parseLong(s,16) and Long.toHexString(l) not inverses?

I get this but yet I don't get it:
package com.example.bugs;
public class ParseLongTest {
public static void main(String[] args) {
long l = -1;
String s = Long.toHexString(l);
System.out.println(s);
long l2 = Long.parseLong(s, 16);
}
}
This fails with the following:
ffffffffffffffff
Exception in thread "main" java.lang.NumberFormatException: For input string: "ffffffffffffffff"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
at java.lang.Long.parseLong(Long.java:410)
at java.lang.Long.parseLong(Long.java:468)
at com.example.bugs.ParseLongTest.main(ParseLongTest.java:8)
presumably because if you literally interpreted 0xffffffffffffffffL, it would not fit in the Long number space, which is signed.
But why does Long.toHexString() produce a string that cannot be parsed by Long.parseLong(), and how do I work around this? (I need a way of getting long values to their hex string representation, and back again)
Long.parseLong(String s, int radix) doesn't understand two's complement. For negative number it expects minus sign. As bestsss already mentioned you should use Long.toString(long l, int radix) to make hex string compatible with this parsing method.
This is a known bug, it is fixed in 1.8, see http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4215269
You can use guava's UnsignedLongs.parseUnsignedLong(String s, int radix) if Java 1.8 is not an option.

Categories