I'm trying to loop through numbers from -6 to 38, and output the odd numbers into an array. I don't know how to store the output into an array.
for (int i = -6; i<38; i++){
if (i%2!=0){
**output to array**
}
}
I'm trying to loop through numbers from -6 to 38, and output the odd numbers into an array. I don't know how to store the output into an array.
for (int i = -6; i<38; i++){
if (i%2!=0){
**output to array**
}
}
Because we are not able to know how many the number of the odd numbers is, so you can use IntStream to fix this issue if your java version is 8 or above.
int[] array = IntStream.range(-6, 38).filter(x -> x % 2 != 0).toArray();
Or you can use ArrayList
List<Integer> list = new ArrayList<>();
for (int i = -6; i < 38; i++) {
if (i % 2 != 0) {
list.add(i);
}
}
As the number to elements in array can not be always defined in advance. You can create a list and then convert that to array as below:
List<Integer> oddNumbers = new ArrayList<>();
for (int i = -6; i<38; i++){
if (i%2!=0){
oddNumbers.add(i);
}
}
Integer[] result = oddNumbers.toArray(new Integer[oddNumbers.size()]);