Is there a way to declare an array with an unknown length? My problem is to return an int[] of odd integers from a range of numbers. My current output is adding 0s to fill up the remaining space of the array.
public class Practice {
static int[] oddNumbers(int minimum, int maximum) {
int[] arr = new int[10];
int x = 0;
int count = 0;
for(int i = minimum; i <= maximum; i++){
if(i % 2 != 0){
arr[x] = i;
++x;
}
}
return arr;
}
public static void main(String[] args) {
int min = 3, max = 9;
System.out.println(Arrays.toString(oddNumbers(min, max)));
}
}
My current output is [3,5,7,9,0,0,0,0,0,0] but I'd like it to be 3,5,7,9 It has to be an array and not an ArrayList. Is this possible? Or is there a complete different approach?
Well, in your use case, you know exactly how many numbers you need. Look up how to find the number of odd numbers between two number based on your minimum and maximum. Then just allocate that many:
int closestMin = minimum % 2 == 0 ? minimum + 1 : minimum;
int closestMax = maximum % 2 == 0 ? maximum - 1 : maximum;
int numberOfOdds = ((closestMax - closestMin) / 2) + 1;
int[] arr = new int[numberOfOdds];
....
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With