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());
}
}
}
}
The solution to the above problem in java is as follows:-
Code-
import java.util.*;
interface ScoreIterator {
int next();
boolean hasNext();
}
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);
}
}
}
ScoreIterator scoreIterator () {
// return anonymous
object of type ScoreIterator
ScoreIterator x= new
ScoreIterator(){ //Create new object
int i=0; //devclare player index
int j=0; //Score index
@Override
public int next(){ //Calculate scores for the index
int score=scores[i][j];
j++;
if(j==scores[i].length){
i++; ///increase iterator
j=0;
}
return score; //return total score
}
@Override
public boolean hasNext(){ //Check if new player exists
return i<scores.length;
}
};
return x;
}
public static void main(String[] args)
{
ScoreBoard sb = new
ScoreBoard (3, 2);
ScoreIterator iterator =
sb.scoreIterator ();
while
(iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
Code Screenshots-

Outputs-

Feel free to comment for any issues, do rate the answer positively