I'm doing my homework for Data Structures and I'm having trouble with 2D Array. Here's what I have to do:
"Suppose you are designing a multiplayer game that has n≥1000 players, numbered 1 to n, interacting in an enchanted forest. The winner of this game is the first player who can meet all the other players at least once (ties are allowed). Assuming that there is a method meet(i, j), which is called each time a player i meets a player j (with i ̸= j), describe a way to keep track of the pairs of meeting players and who is the winner."
I can't compile because of this error:
Multiplayer.java:51: error: constant expression required
for this line:
case meet: sb.append("1");
I'm a beginner so I really appreciate any help. Thank you in advance!
/* Suppose you are designing a multiplayer game that has n≥1000
players, numbered 1 to n, interacting in an enchanted forest. The winner
of this game is the first player who can meet all the other players at
least once (ties are allowed). Assuming that there is a method meet(i,
j), which is called each time a player i meets a player j (with i ̸=
j), describe a way to keep track of the pairs of meeting players and
who is the winner. */
public class Multiplayer {
int n; // number of players
int map[][] = new int[n][n]; // create a 2D array
int meet = 1;
int notMeet = 0;
int[] count; // an array to keep the count, player wins when it reaches n
public Multiplayer() {
clearMap();
} // initiate a new game
public void clearMap() { // clear the 2d array
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
map[i][j] = notMeet; // clearing the map
count[i] = 0; // turn every value of count[] into 0
if (i == j)
map[i][j] = map[j][i] = meet; // when i == j give the tile the value of 1
}
}
}
public void meet(int i, int j) {
// when player i meets player j, add 1 to the count[] of each player
count[i] = count[i] + 1;
count[j] = count[j] + 1;
}
public int isWin() {
for (int i = 0; i < n; i++) {
if (count[i] == n)
return i; // player at the index i wins
}
return -1; // no player won yet
}
public String toString() {
// display the map in string
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
switch (map[i][j]) {
case meet:
sb.append("1"); // if player i and j meets, put 1 in the map //this line causes error
default:
sb.append("0"); // if they haven't met, put the 0 as default
}
if (j < n - 1)
sb.append("|");
}
if (i < n - 1)
sb.append("\n-----\n");
}
return sb.toString();
}
}
class MultiplayerTest {
public static void main(String[] args) {
Multiplayer newGame = new Multiplayer();
newGame.n = 5; // test for a small number of players
// test for player 1 to meet all other players
for (int i = 2; i <= 5; i++) {
newGame.meet(1, i);
}
// print test to see if player 1 wins the game
System.out.println(newGame.toString());
System.out.println(newGame.isWin());
}
}