Welcome to the Java Programming Forums

The professional, friendly Java community. 21,500 members and growing!

The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.

>> REGISTER NOW TO START POSTING

1. ## Problem with arrays

I am a beginner and my teacher assigned us a problem where we are given an array named arr. We are supposed to create a new array that only has the odd values from arr. This is my code:
```public int [] youMakeMeOdd(int [] arr)
{
int[] ans = new int[arr.length];
for (int i = 0; i<arr.length; i++)
{
if(arr[i] % 2 != 0)
{
ans[i] = arr[i];
}
}
return ans;
}```
However, say for example that arr had only even integers to begin with. My new array will be filled with 0's.
But it is supposed to not have the zeros.

Say arr was {2,4,5,6}. My new array should be {5}. Instead it is{0,0,5,0}. I need a way to get rid of the zeros. Any help would be appreciated.

2. ## Re: Problem with arrays

you can make a count of how many odd integers there are first. After that you can initialize the ans array with that count size. Then go through the array again and store the odd number. Or you can use ArrayList if your teacher doesn't forbid.

3. ## Re: Problem with arrays

ArrayLists are forbidden so that's a no go. This might sound a little dumb, but how do I count the odd integers?

4. ## Re: Problem with arrays

First i would like to tell problem with your code ,see all the elements of the array are initalized with value o
when you define it.
Now you are adding lement whenever any odd no found so it could be in any index position within your array so
ans[i] = arr[i];
this line is storing odd no at original index as in the input array.

```public int [] youMakeMeOdd(int [] arr)
{
int[] ans = new int[arr.length];
int k=0;

for (int i = 0; i<arr.length; i++)
{
if(arr[i] % 2 != 0)
{
ans[k] = arr[i];
k++;

}
}
return ans;
}```
Say arr was {2,4,5,6}. My new array should be {5}. Instead it is{0,0,5,0}. I need a way to get rid of the zeros. Any help would be appreciated.
In the modified code above
Output for this input will be {5,0,0,0}
now you can display elements upto first zero found.

for(int i=0;i<ans.length;i++){
System.out.println(ans[i]);
if(ans[i] == 0)
break;
}