millionclones
millionclones

Reputation: 19

How do I combine the first element of 2 array together into a string array?

    String quantityArray[] = GetStringArray(quantity);
    String foodItemArray[] = GetStringArray(fooditems);

this is to change from ArrayList to a String Array

    int n1 = fooditems.size();
    int n2 = quantity.size();

    for(int s = 0; s<n1;s++){

        totalFood[s] = quantityArray[s] + foodItemArray[s];
    }

I cannot make this totalFood[] function to work as it just keeps crashing my app

public static String[] GetStringArray(ArrayList<String> arr) {
    // declaration and initialise String Array
    String str[] = new String[arr.size()];
    // ArrayList to Array Conversion
    for (int j = 0; j < arr.size(); j++) {
        // Assign each value to String array
        str[j] = arr.get(j);
    }
    return str;
}

The error that pops up is (Attempt to write to null array)

Upvotes: 0

Views: 70

Answers (2)

murari99732
murari99732

Reputation: 159

public static String[] GetStringArray(ArrayList<String> arr) {
        String str[] = new String[arr.size()];
        for (int j = 0; j < arr.size(); j++) {
            str[j] = arr.get(j);
        }
        return Arrays.stream(str).filter(s -> s!=null).toArray(String[]::new);
    }

Upvotes: 0

gthanop
gthanop

Reputation: 3311

You need to make sure totalFood array is allocated.

Arrays are themselves Objects in Java.

For example:

totalFood = new String[n1];

This is because totalFood seems to be null according to the error you are seeing. You need to allocate some space (n1 references to be precise for the above example) for the Strings resulting from the concatenation to be stored at. You can take a look at the corresponding Java tutorial here.

Also make sure n1 is equal to n2 which should be equal also to the size of the totalFood array in order to not overrun any of them in your loop.

Finally, there are 2 handy Collection#toArray methods which will do what you are doing in your GetStringArray method. You can use it for example like so:

String quantityArray[] = quantity.toArray(new String[quantity.size()]);

Using the toArray method seems not to be related to the problem, but I just mention it for completeness.

Upvotes: 1

Related Questions