如何返回数组的特定元素? [英] How to return a specific element of an array?

查看:157
本文介绍了如何返回数组的特定元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想返回奇数个数组,但Eclipse似乎不接受我的返回 array [i]; 代码。我认为它需要返回一个完整的数组,因为我将一个数组设置为我的方法的参数。
正如我之前所说的,我需要传递一个数组并获得该数组的特定元素作为回报。即使我将该数组设为静态,如何返回单个元素?

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?

编辑:好的,这就是:

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.

推荐答案

您的代码应如下所示:

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

这里的要点是方法返回类型,它应该与数组元素类型匹配,如果你在 main()工作 - 这个方法也必须是静态的。

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.

这篇关于如何返回数组的特定元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆