0

I have created a function that takes an array and outputs another array. So I have declared the result array (which will be the output) as null cause the size varies and depends on the inputted array. (for eg. if I enter an array of integers and then I want to output the array containing even numbers from that array). So I will be using for or while loops and I want to know that how I can add the integer to that null array. I tried but I get a null pointer exception that says cannot store to int array cause "array" is null.

sorry but I can't use more advanced techniques cause I am new to java (I need to make this without using arraylist library as I am learning coding I found those type of questions which tries to make you perfect in i specific topic and then they take you to next step so u can be more prepared)

I am using this code and I want to know that add an element to my result array or should I initialized it as null or something else cause the size depends on inputted array in this code I am getting null pointer exception

public static int[] even(int[] numbers) {
    int[] result = null;

    int even = 0;
    int i = 0;
    int a = 0;
    while (i < numbers.length) {
        if (numbers[i] % 2 == 0) {
            even = numbers[i];
            result[a] = even;
            a++;
        }
        i++;
    }
    return result;
}
1
  • Sorry you can't "use more advanced technique", because this is a situation where more advanced technique is the correct approach. For example, return Arrays.stream(numbers).filter(x -> x % 2 == 0).toArray(); Commented Feb 12, 2021 at 4:13

2 Answers 2

1

The array's size needs to be initialized. If you want dynamic storage , read about List and Collection.

Here, if you still want to use array, you need the count.

int a = 0;
while (i < numbers.length) {
    if (numbers[i] % 2 == 0) {
        a++;
    }
    i++;
}

Then after this, you can initialize it as int[] result = new int[a];

Sign up to request clarification or add additional context in comments.

Comments

0
public static int[] even(int[] numbers) {
    int[] result = null;

    int j = 0;
    int a = 0;
    while (i < numbers.length) {
        if (numbers[j] % 2 == 0) {
            a++;
        }
        j++;
    }
    result = new int[a];

    int even = 0;
    int i = 0;
    int b = 0;
    while (i < numbers.length) {
        if (numbers[i] % 2 == 0) {
            even = numbers[i];
            result[b] = even;
            b++;
        }
        i++;
    }
    return result;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.