Return array of integers except 0. How do I?

2

The method receives two numbers per parameter, and returns an 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 numbers in the array , and is to return only the odd numbers.

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

How do I return only filled positions? 3 5

    
asked by anonymous 30.07.2017 / 19:23

1 answer

4

You do not need to create an array that fits all generated elements, you can do one with the amount of final elements. But you do not need to filter anything, you can use math to know beforehand which ones are odd. I did not make any necessary validations. It gives even more simplification, 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;
    }
}

See running on ideone . And at Coding Ground . Also I placed in GitHub for future reference .

    
30.07.2017 / 19:54