Return array of integers except 0. How do I do?

Asked

Viewed 276 times

2

The method takes two numbers per parameter, and returns one array with the odd numbers between these two numbers.

public static int[] oddNumbers(int l, int r) {
    int odd[] = new int[r];
    for(int i=0; i<odd.length;i++){
        if(l<=r && l%2!=0){
            odd[i]=l;
        } l++; 
    }
        return odd;
}

However, it is returning the zeros in the array, and is to return only the odd.

At the moment, if put oddNumbers(2,5), the result will be: 0 3 0 5 0

How do I return only filled positions? 3 5

  • Yes, because an integer array is started with all fields like 0. The ones you do not fill continue with this value.

  • Yes, yes. But is there any way to return only the filled fields?

  • Creating an array only with the amount of values you need to return or using Arraylist.

  • 1

    You want to return one array that returns the odd between l and r, that’s it?

  • @Daniel filled in with that?

  • @exact bigown, an array that returns the odd between l and r.

Show 1 more comment

1 answer

4


No need to create a array that fits all the generated elements, can make one with the amount of final elements. But you don’t need to filter anything, you can use math to know beforehand which are the odd ones. I haven’t made necessary validations. You can even simplify more, but not to complicate too much for beginners is this:

class HelloWord {
    public static void main (String[] args) {
        for (int i : oddNumbers(2, 5)) System.out.println(i);
    }

    public static int[] oddNumbers(int l, int r) {
        l += 1 - l % 2;
        r -= 1 - r % 2;
        int odd[] = new int[(r - l) / 2 + 1];
        for (int i = 0; i < odd.length; i++) odd[i] = l + (i * 2);
        return odd;
    }
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • It’s working perfectly! Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.