2016-11-05 11 views
0
/* Assume as precondition that the list of players is not empty. 
* Returns the winning score, that is, the lowest total score. 
* @return winning score 
*/ 
public int winningScore() { 
    Player thePlayer = players.get(0); 
    int result = thePlayer.totalScore(); 
    for (int i = 0; i < players.size(); i++){ 
     int p = players.get(i).totalScore(); 
     if (p < result) { 
      result = players.get(i).totalScore(); 
     } 
    } 
    return result; 
} 

/* Returns the list of winners, that is, the names of those players 
* with the lowest total score. 
* The winners' names should be stored in the same order as they occur 
* in the tournament list. 
* If there are no players, return empty list. 
* @return list of winners' names 
*/ 
public ArrayList<String> winners() { 
    ArrayList<String> result = new ArrayList<String>(); 

    for (int i = 0; i < players.size(); i++) 
     if (!players.isEmpty()) 
      return result; 
} 

コメントに記載されているように、winnersメソッドでwinningScore()の結果を返そうとしているため、勝者/勝者の名前が返されます。あるメソッドから別のメソッドに値を返す

私はすべての受賞者のみを返すことができましたが、winningScore()メソッドから呼び出す必要がある場合は少し混乱していますか?

私は私の現在のコードが正しい方向に任意のプッシュ/ヒントをいただければ幸い勝者

に対して不適切であることを理解!ありがとう!

+0

:あなたはi変数インデックスを使用していないので、 'int scoreToMatch = winningScore();'その後、すべてのプレイヤーをループし、どれが*そのスコアを持っているかを確認します。 –

+0

@Jon Skeetありがとう! – copernicon1543

答えて

1

あなたがしたいことは、勝者方法で勝ちスコアを持つすべての選手オブジェクトを見つけることです。

  • これを行うには、まず winningScoreメソッドを呼び出すことによって勝ち点を計算する必要があります。
  • 次にtotalScoreが と以前に計算された勝率に等しいすべての選手オブジェクトを見つけます。あなたはそれらを戻したいと思います。

あなたの勝者メソッドの結果のコードは次のようになります。

public ArrayList<String> winners() { 
    ArrayList<String> result = new ArrayList<String>(); 

    int winningScore = winningScore(); 

    for (int i = 0; i < players.size(); i++) 
     if (players.get(i).totalScore() == winningScore) 
      result.add(players.get(i).getName()) 

    return result; 
} 

あなたはコードを単純化したい場合、あなたはこのようなArrayListイテレータを使用してループによってforループを置き換えることができ、あなたが...例えば開始する `勝者()`メソッドから `)(` winningScoreを呼ぶべきであるようにまあそれは見た目

for (Player player : players) { 
    if (player.totalScore() == winningScore) 
     result.add(player.getName()) 
} 
+0

ありがとう!これは、明確にするために、プレイヤーのリストをループして、winningScoreメソッドとtotalScoreを比較して、勝者名をArrayListに追加します結果= new ArrayList ()? – copernicon1543

+0

空のリストを返すには、戻り値を呼び出すだけですか? – copernicon1543

+0

コメントありがとうございます。これで、プレーヤー名が(プレーヤーオブジェクトのgetName()メソッドを介して)結果リストに追加されます。通常は、文字列リストの代わりにArrayList を返すことをお勧めします。これは、文字列リストだけでなく、プレイヤーリストで多くのことができるためです。 – biro

関連する問題