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()); } } }
}
ScoreBoard.java
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 () {
ScoreIterator scoreiterator = new ScoreIterator() {
private int row = 0;
private int column = 0;
private int totalrows = scores.length;
private int totalcolumns = scores[0].length;
@Override
public int next() {
//check if we have next element
if (hasNext()) {
while (row < totalrows) {
while (column < totalcolumns) {
int num = scores[row][column];
column++;
if (column == totalcolumns) {
column = 0;
row++;
}
return num;
}
row++;
}
}
return 0;
}
@Override
public boolean hasNext() {
return row < totalrows && column < totalcolumns;
}
};
return 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());
}
}
}
ScoreIterator.java
public interface ScoreIterator {
int next();
boolean hasNext();
}