How to return a specific element of an array?

2

I want to return odd numbers of an array yet Eclipse doesn't seem to accept my return array[i]; code. I think it requires returning a whole array since I set an array as a parameter to my method. As I said before, I need to pass an array and get a specific element of that array in return. Even if I make that array static, how do I return a single element?

Edit : Alright then, here it is:

public class newClass{
public static void main(String[] args) 
{       
    int [] newArray= new int [4];
    int [] array = {4,5,6,7};

    newArray[0] = array[0]+array[1]+array[2]+array[3];
    newArray[1] = array[0]*array[1]*array[2]*array[3];
    newArray[2] = findOut(array);

}

public static int findOut (int [] array3)
{
    int e1=0;
    int e2=0;
    for (int i=0; i<array3.length; i++)
    {
        if (array3[i]%2==0)
        {
            e1+=array3[i];
            array3[i]=e1
            return array3[i];
        }

        else
        {
            e2+=array3[i];
            array3[i]=e2;
            return array3[i];

        }

    }

}


}

I know there are probably more than a few mistakes here but I'm working on it and I'm not only returning odd numbers, I also add them together.

This question is tagged with java arrays parameters elements

~ Asked on 2013-10-15 08:41:40

The Best Answer is


11

You code should look like this:

public int getElement(int[] arrayOfInts, int index) {
    return arrayOfInts[index];
}

Main points here are method return type, it should match with array elements type and if you are working from main() - this method must be static also.

~ Answered on 2013-10-15 08:47:48


3

I want to return odd numbers of an array

If i read that correctly, you want something like this?

List<Integer> getOddNumbers(int[] integers) {
  List<Integer> oddNumbers = new ArrayList<Integer>();
  for (int i : integers)
    if (i % 2 != 0)
      oddNumbers.add(i);
  return oddNumbers;
}

~ Answered on 2013-10-15 08:53:47


Most Viewed Questions: