简体   繁体   中英

Converting string array to int with a delimiter

I can't figure out why I'm getting a null pointer exception. I'm trying to convert a line numbers that the user enters after a prompt, and I want to deliminate it either a space " " a comma "," or a comma and a space ", ".

Here's my code, I'm getting a null pointer exception on the nums[i]=Integer.parseInt(holder[i]); line. I just can't figure out why.

String again="n";
    int[] nums = null;

    do {
        Scanner scan = new Scanner (System.in);

        System.out.println("Enter a sequence of integers separated by a combination of commas or spaces: ");
        String in=scan.nextLine();
        String[] holder=in.split(",| |, ");

            for (int i=0; i<holder.length; i++) {

                nums[i]=Integer.parseInt(holder[i]);
                System.out.print(nums[i]);
            }


    }
    while (again=="y");

Ok Thanks everyone, I got it working by initializing the length of the nums array to the length of the holder array as suggested in the accepted answer. Like this:

int[] nums = new int[holder.length];

I have a second question though, as my regex seems to be failing, I can get it to read if delineated by "," or by " " but not by ", " any ideas?

Here's my error:

Enter a sequence of integers separated by a combination of commas or spaces: 
    1, 2, 3
    Exception in thread "main" 1java.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 SortComparison.main(SortComparison.java:20)

Your null pointer exception is caused by the fact that you have initialized the nums array to null, then try to "point" to it in your for loop. You can lose int[] nums = null and add:

int[] nums = new int[holder.length];

immediately before the for loop (after you've created the holder array, obviously).

You have set

int[] nums = null;

and then try to access

num[i]

which gives you the NullPointerException. You first need to contruct the array to hold the required number of elements:

int[] nums = new int[holder.length] 

You better print your holder[i] before parsing it into an Integer, to see what's in it. I am guessing that holder[i] is not having a valid value for an Integer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM