Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

java - How to return a specific element of an array?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...