Hint
In the setter for the game allow only "poker", "blackjack" and "roulette". The class Casino keeps an array of players inside it. For mostProfitableGame() count the players in the minus (balance < 0) for each game and return the game with the largest count; for an equal count the one found earlier stays (comparison with >, not >=).
Solution (Java)
class Player {
private String name;
private String game;
private int balance;
Player(String name, String game, int balance) {
this.name = name;
setGame(game);
this.balance = balance;
}
String getGame() { return game; }
int getBalance() { return balance; }
void setGame(String game) {
if (game.equals("poker") || game.equals("blackjack") || game.equals("roulette")) {
this.game = game;
} else {
System.out.println("Game not allowed: " + game);
this.game = "poker"; // the default value
}
}
public String toString() {
return name + " plays " + game + " and has " + balance + " in the account.";
}
}
class Casino {
private Player[] players;
Casino(Player[] players) {
this.players = players;
}
public String toString() {
String s = "";
for (Player p : players) s += p.toString() + "\n"; // calls toString of every player
return s;
}
String mostProfitableGame() {
String best = null;
int max = 0;
for (Player p : players) { // in the order in which we come across the games
if (p.getBalance() >= 0) continue;
int count = 0;
for (Player q : players) {
if (q.getBalance() < 0 && q.getGame().equals(p.getGame())) count++;
}
if (count > max) { // > : for an equal count the first one found stays
max = count;
best = p.getGame();
}
}
return best == null ? "none (nobody is in the minus)" : best;
}
}
public class CasinoGames {
public static void main(String[] args) {
Player[] players = {
new Player("Toma", "poker", 75000),
new Player("Nikola", "blackjack", 23000),
new Player("Ana", "roulette", -5000),
new Player("Marko", "blackjack", -1200),
new Player("Jovan", "roulette", -300),
};
Casino casino = new Casino(players);
System.out.print(casino);
System.out.println("The most profitable game: " + casino.mostProfitableGame());
}
}
Output:
Toma plays poker and has 75000 in the account.
Nikola plays blackjack and has 23000 in the account.
Ana plays roulette and has -5000 in the account.
Marko plays blackjack and has -1200 in the account.
Jovan plays roulette and has -300 in the account.
The most profitable game: roulette