Mzq
Mzq

Reputation: 1854

java BigInteger manipulation

The following code is for debugging:

public static void main(String[] args) {
    BigInteger n = new BigInteger("10000000001");
    String sn = n.toString();
    char[] array = sn.toCharArray();
    //intend to change value of some char in array
    //not standard math operation
    BigInteger result = new BigInteger(array.toString());
}

It gives me error:

    Exception in thread "main" java.lang.NumberFormatException: For input string: "[C@86c347"
        at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
        at java.lang.Integer.parseInt(Integer.java:449)
        at java.math.BigInteger.<init>(BigInteger.java:316)
        at java.math.BigInteger.<init>(BigInteger.java:451)
        at debug.main(debug.java:14)

But it was working fine, until this case, I'm not quite sure what went wrong.

Upvotes: 0

Views: 1779

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1499790

When in doubt, add more diagnostics... taking out statements which do two things. This:

array.toString()

won't do what you expect it to, because arrays don't override toString(). It'll be returning something like "[C@89ffb18". You can see this by extracting an extra local variable:

BigInteger n = new BigInteger("10000000001");
String sn = n.toString();
char[] array = sn.toCharArray();
String text = array.toString();
BigInteger result = new BigInteger(text);

Then in the debugger you should easily be able to look at the value of text before the call to BigInteger - which would show the problem quite clearly.

To convert a char array to a string containing those characters, you want:

new String(array)

Upvotes: 4

Related Questions