In: Computer Science
In java. I have class ScoreBoard that holds a 2d array of each player's score. COde Bellow
Example:
Score 1 | score 2 | |
Player1 | 20 | 21 |
Player2 | 15 | 32 |
Player3 | 6 | 7 |
Using the method ScoreIterator so that it returns anonymous object of type ScoreIterator , iterate over all the scores, one by one. Use the next() and hasNext() public interface ScoreIterator { int next(); boolean hasNext();
Class ScoreBoard :
import java.util.*; public class ScoreBoard { int[][] scores ; public ScoreBoard (int numOfPlayers, int numOfRounds) { scores = new int[numOfPlayers][numOfRounds]; Random rand = new Random(); for (int i = 0; i < numOfPlayers; i++) { for (int j = 0; j < numOfRounds; j++) { scores [i][j] = 50 + rand.nextInt(51); } } } public ScoreIterator scoreIterator () { // return anonymous object of type ScoreIterator } public static void main(String[] args) { ScoreBoard sb = new ScoreBoard (3, 2); ScoreIterator iterator = sb.ScoreIterator (); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
}
Here is the updated class ScoreBoard. ============================================================================= import java.util.*; public class ScoreBoard { int[][] scores; int nextIndex = 0; public ScoreBoard(int numOfPlayers, int numOfRounds) { scores = new int[numOfPlayers][numOfRounds]; Random rand = new Random(); for (int i = 0; i < numOfPlayers; i++) { for (int j = 0; j < numOfRounds; j++) { scores[i][j] = 50 + rand.nextInt(51); } } nextIndex = 0; } public ScoreIterator ScoreIterator() { return new ScoreIterator() { @Override public int next() { int score = scores[nextIndex/scores[0].length][nextIndex%scores[0].length]; nextIndex++; return score; } @Override public boolean hasNext() { return (nextIndex < scores.length * scores[0].length); } }; } public static void main(String[] args) { ScoreBoard sb = new ScoreBoard(2, 3); ScoreIterator iterator = sb.ScoreIterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
=====================================================================