+1 (315) 557-6473 

Create a Program to Implement Vectors and Arrays in Java Assignment Solution.


Instructions

Objective
Write a java assignment program to implement vectors and arrays.

Requirements and Specifications

Assignment Overview
This assignment focuses on the design, implementation and testing of C++ programs to process data files using arrays and vectors as described below.
For full credit it must be completed no later than 6:00 am on Monday, March 22. You may turn the program in up to two days late 6:00am on Wednesday, March 24 for -30 points. . No programs will be accepted after that time so do not wait until the last minute to get started. Writing programs usually take longer than you think.
Assignment Specifications
DO NOT USE CLASSES.
Please use getline and vectors to sort through the file.
You will develop a C++ program to store and manage information about baseball players. The program will read the following information for each player in the data file:
player’s name (string)
team identifier (string)
games played (integer)
at bats (integer)
runs scored (integer)
hits (integer)
doubles (integer)
triples (integer)
homeruns (integer)
Separate parallel vectors should be used to store the Player’s name and the Team identifier.
For each player, your program will compute the batting average and the slugging percentage. Those computed values will be stored in separate corresponding parallel arrays. The following formulas will be used for those computations:
singles = hits - (doubles + triples + homeruns)
total bases = singles + 2*doubles + 3*triples + 4*homeruns
batting average = (hits) / (at bats)
slugging percentage = (total bases) / (at bats)
A player with zero at bats is defined to have a batting average and slugging percentage of zero.
Note that only name, team identifier, batting average and the slugging percentage are stored and retained in the vectors and arrays.
The program will recognize the following commands:
QUIT
INPUT filename
TEAM identifier
REPORT n BATTING
REPORT n SLUGGING
The program will recognize commands entered with any mix of upper and lowercase letters.
The program will be operated interactively: it will prompt the user and accept commands from the keyboard and continue until QUIT is entered.
If the user enters an invalid command, the program will display an appropriate message and prompt the user to enter another command.
The “QUIT” command will halt execution.
The "INPUT" command will be followed by a string representing the name of an input file. The program will discard the current data set stored in memory, and then process the input file as the source for a new data set (open the file, read the file and for each line store the data in the appropriate vectors or arrays.
An input file contains zero or more player records, where each record is on one line and consists of the nine fields listed above. The fields are separated by semicolons.
If the user enters an invalid file name, the program will display an appropriate message and prompt the user to enter another file name. The program will halt after the user enters an invalid file name three consecutive times.
The "TEAM" command will be followed by a string representing a team identifier. The program will display all information about all players on that team, in alphabetical order.
The information will be displayed in tabular form. The fields will be identified using column headers, and the fields will be aligned beneath the headers.
If the user enters an invalid team identifier, the program will display an appropriate message and prompt the user to enter another command; the program will not display an empty table.
Source Code
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
// Function prototypes
int calculateSingles(int hits, int doubles, int triples, int homeruns);
int calculateTotalBases(int singles, int doubles, int triples, int homeruns);
double calculateBattingAverage(int hits, int atBats);
double calculateSluggingPercentage(int totalBases, int atBats);
bool loadData(const string &filename, vector &playerNames, vector &teamIds,
vector &gamesPlayed, vector &atBats, vector &runsScored, vector &runs,
vector &hits, vector &doubles, vector &triples, vector &homeruns);
void printData(vector &playerNames, vector &teamIds,
vector &gamesPlayed, vector &atBats, vector &runsScored, vector &runs,
vector &hits, vector &doubles, vector &triples, vector &homeruns,
const string &teamIdFilter, int limit);
void swapData(vector &strings, int i, int j);
void swapData(vector &ints, int i, int j);
void sortData(vector &playerNames, vector &teamIds,
vector &gamesPlayed, vector &atBats, vector &runsScored, vector &runs,
vector &hits, vector &doubles, vector &triples, vector &homeruns,
const string &sortType, bool ascending);
bool searchTeamId(const vector &teamIds, const string &teamId);
// Entry point
int main()
{
// Initialize our containers
vector playerNames;
vector teamIds;
vector gamesPlayed;
vector atBats;
vector runsScored;
vector runs;
vector hits;
vector doubles;
vector triples;
vector homeruns;
// Load data from file
while (true)
{
// Let the user enter a command
cout << "> ";
string line;
getline(cin, line);
// Make the command lowercase so comparison is case insensitive
transform(line.begin(), line.end(), line.begin(), ::tolower);
// Extract the command
stringstream ss(line);
string command;
if (ss >> command)
{
if (command == "quit")
{
// Exit
break;
}
else if (command == "input")
{
if (command.size() + 1 >= line.length()) {
cout << "Invalid command." << endl;
continue;
}
int failedAttempts = 0;
while (failedAttempts < 3)
{
// Load data, we get the filename and load it
string filename = line.substr(command.size() + 1);
if (loadData(filename, playerNames, teamIds, gamesPlayed, atBats,
runsScored, runs, hits, doubles,
triples, homeruns))
{
cout << "Data loaded." << endl;
break;
}
else
{
cout << "Failed to load data." << endl;
failedAttempts++;
if (failedAttempts < 3)
cout << "Try again: ";
}
}
// Halt if attempts has failed 3 times
if (failedAttempts >= 3)
{
cout << "Failed to load data 3 times. Halting program." << endl;
break;
}
}
else if (command == "team")
{
// Get the team identifier
string teamId = line.substr(command.size() + 1);
if (searchTeamId(teamIds, teamId))
{
// Sort by name and print out only those that are on the given team
sortData(playerNames, teamIds, gamesPlayed, atBats,
runsScored, runs, hits, doubles,
triples, homeruns, "name", true);
printData(playerNames, teamIds, gamesPlayed, atBats,
runsScored, runs, hits, doubles,
triples, homeruns, teamId, -1);
}
else
{
cout << "The team does not exist." << endl;
}
}
else if (command == "report")
{
// Get the limit
stringstream ss(line.substr(command.size() + 1));
int limit;
string reportType;
if (ss >> limit >> reportType)
{
// Do the reporting
if (reportType == "hits" || reportType == "batting" || reportType == "slugging")
{
sortData(playerNames, teamIds, gamesPlayed, atBats,
runsScored, runs, hits, doubles,
triples, homeruns, reportType, false);
printData(playerNames, teamIds, gamesPlayed, atBats,
runsScored, runs, hits, doubles,
triples, homeruns, "", limit);
}
}
else
{
cout << "Invalid command." << endl;
}
}
else
{
cout << "Invalid command." << endl;
}
}
}
return 0;
}
// Calculate the singles
int calculateSingles(int hits, int doubles, int triples, int homeruns)
{
return hits - (doubles + triples + homeruns);
}
// Calculate the total bases
int calculateTotalBases(int singles, int doubles, int triples, int homeruns)
{
return singles + 2 * doubles + 3 * triples + 4 * homeruns;
}
// Calculate the batting average
double calculateBattingAverage(int hits, int atBats)
{
if (atBats == 0)
return 0;
return (double)hits / atBats;
}
// Calculate the slugging percentage
double calculateSluggingPercentage(int totalBases, int atBats)
{
if (atBats == 0)
return 0;
return (double)totalBases / atBats;
}
// Load the data of players from file
bool loadData(const string &filename, vector &playerNames, vector &teamIds,
vector &gamesPlayed, vector &atBats, vector &runsScored, vector &runs,
vector &hits, vector &doubles, vector &triples, vector &homeruns)
{
ifstream inFile(filename.c_str());
string line;
if (!inFile.is_open())
{
cout << "Failed to open " << filename << " file" << endl;
return false;
}
// Clear the vectors
playerNames.clear();
teamIds.clear();
gamesPlayed.clear();
atBats.clear();
runsScored.clear();
runs.clear();
hits.clear();
doubles.clear();
triples.clear();
homeruns.clear();
while (getline(inFile, line))
{
stringstream ss(line);
string token;
int number;
// Extract the name
getline(ss, token, ';');
playerNames.push_back(token);
// Extract the team ID
getline(ss, token, ';');
teamIds.push_back(token.substr(1));
// Extract the games played
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
gamesPlayed.push_back(number);
// Extract the at bat
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
atBats.push_back(number);
// Extract the runs scored
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
runsScored.push_back(number);
// Extract the runs
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
runs.push_back(number);
// Extract the hits
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
hits.push_back(number);
// Extract the doubles
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
doubles.push_back(number);
// Extract the triples
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
triples.push_back(number);
// Extract the homeruns
getline(ss, token, ';');
number = atoi(token.substr(1).c_str());
homeruns.push_back(number);
}
inFile.close();
return true;
}
// Print all players in a tabular format
void printData(vector &playerNames, vector &teamIds,
vector &gamesPlayed, vector &atBats, vector &runsScored, vector &runs,
vector &hits, vector &doubles, vector &triples, vector &homeruns,
const string &teamIdFilter, int limit)
{
cout << setw(20) << left << "Player";
cout << setw(5) << left << "Team";
cout << setw(15) << right << "Games Played";
cout << setw(10) << right << "At Bats";
cout << setw(15) << right << "Runs Scored";
cout << setw(10) << right << "Runs";
cout << setw(10) << right << "Hits";
cout << setw(10) << right << "Doubles";
cout << setw(10) << right << "Triples";
cout << setw(10) << right << "Homeruns";
cout << setw(10) << right << "Singles";
cout << setw(15) << right << "Total Bases";
cout << setw(15) << right << "Batting Avg";
cout << setw(15) << right << "Slugging Pct";
cout << endl;
cout << setw(20) << left << "------";
cout << setw(5) << left << "----";
cout << setw(15) << right << "------------";
cout << setw(10) << right << "-------";
cout << setw(15) << right << "-----------";
cout << setw(10) << right << "----";
cout << setw(10) << right << "----";
cout << setw(10) << right << "-------";
cout << setw(10) << right << "-------";
cout << setw(10) << right << "--------";
cout << setw(10) << right << "-------";
cout << setw(15) << right << "-----------";
cout << setw(15) << right << "-----------";
cout << setw(15) << right << "------------";
cout << endl;
for (int i = 0; i < (int)playerNames.size(); i++)
{
// Stop at limit, a -1 limit will display all
if (limit >= 0 && i >= limit)
break;
string someTeamId = teamIds[i];
transform(someTeamId.begin(), someTeamId.end(), someTeamId.begin(), ::tolower);
if (teamIdFilter == "" || someTeamId == teamIdFilter)
{
int singles = calculateSingles(hits[i], doubles[i], triples[i], homeruns[i]);
int totalBases = calculateTotalBases(singles, doubles[i], triples[i], homeruns[i]);
cout << setw(20) << left << playerNames[i];
cout << setw(5) << left << teamIds[i];;
cout << setw(15) << right << gamesPlayed[i];
cout << setw(10) << right << atBats[i];
cout << setw(15) << right << runsScored[i];
cout << setw(10) << right << runs[i];
cout << setw(10) << right << hits[i];
cout << setw(10) << right << doubles[i];
cout << setw(10) << right << triples[i];
cout << setw(10) << right << homeruns[i];
cout << setw(10) << right << singles;
cout << setw(15) << right << totalBases;
cout << fixed;
cout << setw(15) << right << setprecision(2) << calculateBattingAverage(hits[i], atBats[i]);
cout << setw(15) << right << setprecision(2) << calculateSluggingPercentage(totalBases, atBats[i]);
cout << endl;
}
}
}
// Swap string data
void swapData(vector &strings, int i, int j)
{
string temp = strings[i];
strings[i] = strings[j];
strings[j] = temp;
}
// Swap int data
void swapData(vector &ints, int i, int j)
{
int temp = ints[i];
ints[i] = ints[j];
ints[j] = temp;
}
// Sort by field in ascending order
void sortData(vector &playerNames, vector &teamIds,
vector &gamesPlayed, vector &atBats, vector &runsScored, vector &runs,
vector &hits, vector &doubles, vector &triples, vector &homeruns,
const string &sortType, bool ascending)
{
for (int i = 0; i < (int)playerNames.size() - 1; i++)
{
for (int j = i + 1; j < (int)playerNames.size(); j++)
{
int singlesI = calculateSingles(hits[i], doubles[i], triples[i], homeruns[i]);
int totalBasesI = calculateTotalBases(singlesI, doubles[i], triples[i], homeruns[i]);
double battingAvgI = calculateBattingAverage(hits[i], atBats[i]);
double sluggingPctI = calculateSluggingPercentage(totalBasesI, atBats[i]);
int singlesJ = calculateSingles(hits[j], doubles[j], triples[j], homeruns[j]);
int totalBasesJ = calculateTotalBases(singlesJ, doubles[j], triples[j], homeruns[j]);
double battingAvgJ = calculateBattingAverage(hits[j], atBats[j]);
double sluggingPctJ = calculateSluggingPercentage(totalBasesJ, atBats[j]);
bool doSwap = false;
// Set the sort type
if (sortType == "name")
{
if (ascending && playerNames[i] > playerNames[j])
doSwap = true;
else if (!ascending && playerNames[i] < playerNames[j])
doSwap = true;
}
else if (sortType == "batting")
{
if (ascending && battingAvgI > battingAvgJ)
doSwap = true;
else if (!ascending && battingAvgI < battingAvgJ)
doSwap = true;
}
else if (sortType == "slugging")
{
if (ascending && sluggingPctI > sluggingPctJ)
doSwap = true;
else if (!ascending && sluggingPctI < sluggingPctJ)
doSwap = true;
}
else if (sortType == "hits")
{
if (ascending && hits[i] > hits[j])
doSwap = true;
else if (!ascending && hits[i] < hits[j])
doSwap = true;
}
if (doSwap)
{
swapData(playerNames, i, j);
swapData(teamIds, i, j);
swapData(gamesPlayed, i, j);
swapData(atBats, i, j);
swapData(runsScored, i, j);
swapData(runs, i, j);
swapData(hits, i, j);
swapData(doubles, i, j);
swapData(triples, i, j);
swapData(homeruns, i, j);
}
}
}
}
// Search the existence of a team
bool searchTeamId(const vector &teamIds, const string &teamId)
{
for (int i = 0; i < (int)teamIds.size(); i++)
{
string someTeamId = teamIds[i];
transform(someTeamId.begin(), someTeamId.end(), someTeamId.begin(), ::tolower);
if (someTeamId == teamId)
return true;
}
return false;
}