0
votes

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;
    }

}

}

1
Look closely at your error message: For input string: "n" ... you appear to be inputting text somehow. I see nothing wrong with your logic, and it should work for a number string of arbitrary length. - Tim Biegeleisen
I actually replaced that n with the number I was using to avoid confusion, but it appears I only achieved the opposite!. I'll change it back to what it was in the error message, which was "1202020202020202020" - Steven
Well that is larger than the maximum int, so you can't use int or parseInt(). You should just count the characters, which .length() already does, and make sure each one is numeric, if that's your requirement. It isn't in UK for example. - user207421

1 Answers

2
votes

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.