Instructions
Requirements and Specifications
Source Code
PLAYER
/**
* Class to create Player objects
*/
public class Player
{
/**
* Player name
*/
private String name;
/**
* Player's team name
*/
private String teamName;
/**
* Number of goals
*/
private int goals;
/**
Overloaded constrcutor
* @param name String
* @param teamName String
* @param goals int
*/
public Player(String name, String teamName, int goals) {
this.name = name;
this.teamName = teamName;
this.goals = goals;
}
public String getName() {
return this.name;
}
public String getTeamName() {
return this.teamName;
}
public int getGoals() {
return this.goals;
}
public void setName(String newName) {
this.name = newName;
}
public void setTeamName(String newTeamName) {
this.teamName = newTeamName;
}
public void setGoals(int newGoals) {
this.goals = newGoals;
}
@Override
public String toString() {
return String.format("%s (%s): %d goals", getName(), getTeamName(), getGoals());
}
}
LEAGUE
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class League {
private static List players;
public League() {
players = new ArrayList();
}
public static void addPlayer(Player player) {
players.add(player);
}
public static void printLeague() {
// Print all players
for(Player p: players) {
System.out.println(p.toString());
}
}
public static void printAverageScore() {
// Calculate the average score
double avg_score = 0.0;
// Loop through players
for(Player p: players) {
avg_score += p.getGoals();
}
// Calculate avg
avg_score /= (double)players.size();
System.out.println(String.format("The average score is %.2f", avg_score));
}
public static void main(String[] args) throws Exception {
League l = new League();
// Check that a file name was passed via arguments
if(args.length < 1) {
System.out.println("You must give the name of the file containing the players data.");
return;
}
// Get name of file
String file_name = args[0];
// Create Scanner
Scanner reader = new Scanner(new File(file_name));
String line;
while(reader.hasNextLine()) {
// read line
line = reader.nextLine();
// Split
String[] row = line.split(",");
// Get name, team and goals
String name = row[0].strip();
String teamName = row[1].strip();
int goals = Integer.valueOf(row[2].strip());
// Create player object
Player player = new Player(name, teamName, goals);
// Add to list of players
l.addPlayer(player);
}
// print all players
l.printLeague();
// Print average score
l.printAverageScore();
// Close scanner
reader.close();
}
}