2014-04-08 43 views
0

我在練面向對象這裏進入籃球運動員的名字,多少分的得分和籃板搶下數組的最後一個元素。Java的面向對象,訪問中的對象

我怎麼會去通過每個元素對象數組找到與數量均勻點的最後一個球員?

這是我到目前爲止輸入信息的代碼。在我的第二個循環中,我需要做什麼來檢查每個元素,然後顯示符合我的標準的最後一個元素?

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) 
        { 

        } 
      } 
    } 
} 

回答

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]作爲最後一個元素。

+3

您將要開始在'bbArray.length - 1'和你的條件是'指數> = 0' – gla3dr

+0

@ gla3dr感謝; - ) – user2651804

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; 
    } 
} 
1

你已經知道了。

之前創建臨時,未初始化的變量Basketball temp; for循環穿過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); 
       // 
      } 
    } 
}