The first element of the array from args[1].split("")
is an empty string that to my opinion causes the exception java.lang.NumberFormatException
since it cannot be converted to an Integer
Converting a string array to a large number array
-
23-03-2022 - |
题
So, in Java I have a large number in the command argument, let's say 12345678910, and I cannot use bigInteger, and I already did:
String[] g = args[1].split("");
So, my string is put in a string array. But, I cannot use:
int[] ginormintOne = new int[g.length];
for(int n = 0; n < g.length; n++) {
ginormintOne[n] = Integer.parseInt(g[n]);
}
It gives me this:
Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at Ginormint.main(Ginormint.java:67)
I think my numbers are too large for int. Any idea on how to convert it to a large number array?
解决方案 2
其他提示
You are splitting on an empty string. For example,
"123 456".split("")
results in this array:
["" "1" "2" "3" " " "4" "5" "6"]
This is where your exception comes from.
Use Long.parseLong
instead of Integer.parseInt
and a long[]
instead of Long.parseLong
.
But that said, the NumberFormatException
indicates the failure is because you're passing it an empty string. Are you sure you're splitting the string correctly, or that splitting is even necessary? The args
array in main
is already split on spaces, assuming that's where args
is coming from.