-1

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**
    }
    } 
2
  • Does this answer your question? Add element into array java Commented Oct 14, 2020 at 4:57
  • 1
    But what is your problem? Dont you know how to create an array, or how to compute the size it will need upfront? And note: this is really super basic stuff. Any good book (even the bad ones) explain to you how to create arrays. Please understand that this community isnt meant as replacement for you sitting down and doing that learning thing first. Commented Oct 14, 2020 at 5:18

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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()]);

1 Comment

What makes you think that getting the size is the OP's problem?!

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.