[英]Java cycling through objects
我試圖遍歷對象並每次更新變量,我有一個Player類,其中包含以下所有變量:
Name, s1 ,s2, s3,...., s11, total
我想從頭到尾遍歷每個變量,並為每個玩家每次添加分數(所有玩家都在數組列表中)。
我不確定執行此操作的最佳方法是什么,是否可以選擇特定對象,然后根據要添加的對象來添加變量。
如果您需要更多信息,請先詢問並感謝您提供的任何幫助。
public void addScore(int turn, int score){
Player.setScore( turn, score);
}
您可以使用簡單的for在數組列表中循環,如下所示:
ArrayList<Player> players = ...;
for (int i = 0; i < players.size(); i++) {
/*Operations on players[i] = the current player*/
}
要獲取和修改播放器的變量,可以為每個參數創建getter和setter方法,如下所示:
private String name;
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
如果您有很多相同類型的變量(s1,s11),請使用數組:
int[] scores = new int[11];
因此,您可以使用另一個循環。
如果我正確理解了這個問題,那么每個玩家都有一個名字,11個分數和一個總數。 您似乎在問如何遍歷玩家列表並使總數等於11個分數的總和。
一種更常見的方法(使用OO語言)將只是確保總數始終等於11個分數的總和。 (這被稱為“封裝”,是所有面向對象編程背后的基本思想。)這很容易實現(為了便於編程,我將分數放在一個數組中):
public class Player {
private String name ;
private int[] scores ;
private int total ;
public Player(String name) {
this.name = name ;
this.scores = new int[11] ; // all initialized to zero, as is total.
}
public void setScore(int whichScore, int score) {
int change = score - scores[whichScore] ;
scores[whichScore] = score ;
total = total + change ;
}
public int getScore(int whichScore) {
return scores[whichScore] ;
}
public int getTotal() {
return total ;
}
public String getName() {
return name ;
}
public void setName(String name) {
this.name = name ;
}
}
現在您的問題是多余的: total
始終等於分數的總和,因此無需遍歷播放器即可在代碼中的任何位置計算總數。 您可以通過以下方式獲得每個玩家的總數
for (Player p : listOfPlayers) {
System.out.println("Player "+p.getName()+" has total score "+p.getTotal());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.