Java OOP-访问对象数组中的最后一个元素

时间:2014-04-08 22:51:54

标签: java arrays oop object

我正在练习面向对象,输入篮球运动员的名字以及得分和抢篮得分。

我如何浏览对象数组中的每个元素以找到具有均匀分数的最后一个玩家?

这是我到目前为止输入信息的代码。在第二个forloop中我需要做什么来检查每个元素,然后显示符合我标准的最后一个元素?

class basketballObj
{
    public static void main (String[]args)
    {
        Basketball bbArray[];
        String theName;
        int thePoints;
        int theRebounds;
        int index;
        int noOfElements = 0;

        bbArray = new Basketball[3];

        for(index = 0; index < bbArray.length; index++)
            {
                System.out.println("Enter a name ");
                theName = EasyIn.getString();
                System.out.println("Enter points scored ");
                thePoints = EasyIn.getInt();
                System.out.println("Enter rebounds grabbed ");
                theRebounds = EasyIn.getInt();
                bbArray[index] = new Basketball(theName, thePoints, theRebounds);
                noOfElements++; 
            }
        for(index = 0; index < bbArray.length; index++)
            {
                if(bbArray[index].getPoints() % 2 == 0)
                    {

                    }
            }
    }
}

3 个答案:

答案 0 :(得分:4)

如果你想找到最后一个积分均匀的玩家,你实际上并不想要通过每个元素;-)。尝试:

for(index = bbArray.length-1; index >= 0; index--)
        {
            if(bbArray[index].getPoints() % 2 == 0)
                {
                   //add whatever relevant code here.
                   break; //this line breaks the for loop (because you've found a player with an even amount of score
                }
        }

我们从bbArray.length-1开始,因为当数组包含3个元素时,数组是零索引的。这意味着要获得第一个元素,您必须调用bbArray[0]。同样,为最后一个元素调用bbArray[2]

答案 1 :(得分:1)

简单。向后迭代你的数组。

boolean found = false;
for(int index=array.length-1; index>-1 && !found; index--) {
    if(array[index].getPoints()%2 == 0) {
        // found element. Break out of for loop
        found=true;
    }
}

答案 2 :(得分:1)

你几乎得到了它。

在for循环之前创建一个临时的,未初始化的变量Basketball temp;,迭代bbArray,如果满足bbArray[index]条件,则将其设置为if

如果你想保存它所找到的索引,那么也要创建一个int indexFound;

当user2651804建议产生这个时,向后循环:

public class basketballObj
{
    public static void main(String[] args)
    {

    ...

        Basketball temp;
        int indexFound = -1;

    ...


        for(index = bbArray.length - 1; index >= 0; index++)
            {
                if(bbArray[index].getPoints() % 2 == 0)
                    {
                        temp = bbArray[index];
                        indexFound = index;
                        break;
                    }
            }


        //note temp will be null if no scores were even
        //if (temp != null)
        //you can use the above if statement if you don't want to use indexFound

        //you can also just check if indexFound == -1
        if (indexFound != -1)
            {
                System.out.println("Found at index: " + indexFound);
                //
            }
    }
}