Reputation: 41
I've made a little block of code that has the goal of attempting to store all the digits of a number into an array. For example, the number "123" would be stored as {1,2,3}. Everything seems to work fine, except for when the length of the number is larger then 10. Is it something wrong with my method? The exact error message is
Exception in thread "main" java.lang.NumberFormatException: For input string: "1202020202020202020" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at test.main(test.java:8)
public class test {
public static void main(String[] args){
//This block of code parses the zipcode and stores each number it has into an array. It also fetches the length, which is used later.
String input = args[0];
int length = input.length();
int zipcode = Integer.parseInt(args[0]);
int[] digits = new int[length];
for(int i = 0; i < length ; i++){
digits[i] = zipcode % 10;
zipcode = zipcode /10;
}
}
}
Upvotes: 0
Views: 77
Reputation: 23099
The largest number your code will handle is Integer.MAX_VALUE, which is 2147483647. Beyond that, you're trying to parse a number that won't fit in an Integer. Using a Long will give you a lot more room.
Just saw @user207421's comment, and he/she is right...you really don't need to ever store your string as a numeric value. If you had to, and wanted to handle very large numbers, you could use BigDecimal.
Also, per what you say you want, I think your final array is going to be in the reverse order of what you want.
Upvotes: 2