Programming Task
We've created a simple multiplayer card game called "Add 'Em Up" where 5 players are dealt 5 cards from a standard 52 card pack, and the winner is the one with the highest score. The score for each player is calculated by adding up the card values for each player, where the number cards have their face value, J = 11, Q = 12, K = 13 and A = 1 (not 11). In the event of a tie, list all winners.
You are required to write a program that will read the data from the scanner, find the winner(s) and write them to the console.
Input Structure
The input will contain 5 rows, one for each player's hand of 5 cards. Each row will contain the player's name separated by a colon then a comma separated list of the 5 cards. Each card will be 2 characters, the face value followed by the suit (S = Spades, H = Hearts, D = Diamonds and C = Clubs).
E.g.
Name1:AH,3C,8C,2S,JD
Name2:KD,QH,10C,4C,AC
Name3:6S,8D,3D,JH,2D
Name4:5H,3S,KH,AS,9D
Name5:JS,3H,2H,2C,4D
The first row means:
AH = Ace of Hearts; (A♥)
3C = 3 of Clubs; (3♣)
8C = 8 of Clubs; (8♣)
2S = 2 of Spades; (2♠)
JD = Jack of Diamonds; (J♦)
Output Structure
The output should contain a single line, with one of the following 2 possibilities:
• The name of the winner and their score (colon separated).
• A comma separated list of winners in the case of a tie and the score (colon separated).
E.g.
NameX:40
// or
NameX,NameY:35
--------------------------------------------------------------------------------------------------------------------------------
The code is below:
--------------------------------------------------------------------------------------------------------------------------------
public class Task {
public static void main(String[] args) {
String[] players = new String[5];
players[0] = "James:AH,3C,8C,2S,JD";
players[1] = "Mary:KD,QH,TC,4C,AC";
players[2] = "Brian:6S,8D,3D,JH,2D";
players[3] = "Emma:5H,3S,KH,AS,9D";
players[4] = "John:JS,3H,2H,2C,4D";
int biggest = 0;
String winner = "";
for (String player : players) {
String[] nameCards = player.split(":");
String name = nameCards[0];
String cards = nameCards[1];
int points = calculatePoints(cards);
System.out.println(name + " " + cards + " = " + points);
if (points > biggest) {
biggest = points;
winner = name;
} else if (points == biggest) {
winner = winner + "," + name;
}
}
System.out.println(winner + ":" + biggest);
}
public static int calculatePoints(String cards) {
String[] cardArray = cards.split(",");
int points = 0;
for (String card : cardArray) {
String value = card.substring(0, 1);
if (value.equals("A")) {
points += 1;
} else if (value.equals("T")) {
points += 10;
} else if (value.equals("J")) {
points += 11;
} else if (value.equals("Q")) {
points += 12;
} else if (value.equals("K")) {
points += 13;
} else {
points += Integer.parseInt(value);
}
}
return points;
}
}