canugivemeaname
canugivemeaname

Reputation: 13

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

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!!!

Upvotes: 0

Views: 1730

Answers (4)

Sagar Gangwal
Sagar Gangwal

Reputation: 7947

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.

Upvotes: 0

Jens
Jens

Reputation: 69450

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

Upvotes: 1

Almas Abdrazak
Almas Abdrazak

Reputation: 3612

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

Upvotes: 0

ernest_k
ernest_k

Reputation: 45319

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

Rather use Long.parseLong

Upvotes: 1

Related Questions