You are required, but not limited, to turn in the following source files:
Assignment8.java(More code need to be added)
Athlete.java(given by the instructor, it needs to be modified for this assignment)
AthleteNameComparator.java
MedalCountComparator.java
Sorts.java
AthleteManagement.java
Class Diagram:
Athlete
The Athlete class implements the \"Serializable\" interface so that its object can be stored. (The
Serializable interface is defined in the \"java.io\" package.)
AthleteNameComparator
The AthleteNameComparator class implements the \"Comparator\" interface (The Comparator
interface is in \"java.util\" package.). It needs to define the following method that was an
inherited abstract method from Comparator interface:
public int compare(Object first, Object second)
(Note that you can also define:
public int compare(Athlete first, Athlete second)
instead by making the class implements Comparator.
If the first argument object has a last name lexicographically less than that of the second
argument, an int less than zero is returned. If the first argument object has a last name
lexicographically larger than that of the second argument, an int greater than zero is returned. If
their last names are same, then their first names should be compared. If they have same first and
last names, then 0 should be returned.
MedalCountComparator
The MedalCountComparator class implements the \"Comparator\" interface (The Comparator
interface is in \"java.util\" package.). It needs to define the following method that was an
inherited abstract method from Comparator interface:
public int compare(Object first, Object second)
(Note that you can also define:
public int compare(Athlete first, Athlete second)
instead by making the class implements Comparator.
If the first argument object has a larger gold medal count than that of the second argument, an int
less than zero is returned. If the first argument object has a smaller gold medal count than that of
the second argument, an int greater than zero is returned. If both gold medal counts are same,
then their silver medal counts should be compared. If both gold medal counts are same and also
silver medal counts are same, then their bronze counts should be compared. If all of gold, silver,
and bronze medal counts are same, then 0 should be returned.
Sorts
The Sorts class is a utility class that will be used to sort a list of Athlete objects. Sorting
algorithms are described in the algorithm note posted under Notes section of the course web site.
These algorithms sort numbers stored in an array. It is your job to modify it to sort objects stored
in an array list (or a vector).
The Sorts class object will never be instantiated. It must have the following methods:
public static void sort(ArrayList objects, Comparator)
Your sort method utilizes the compare method of the parameter Comparator object to sort. You
can use one of Selection sort or Insertion Sort.
AthleteManagement
The AthleteManagement class has a list of Ath.
You are required, but not limited, to turn in the following source f.pdf
1. You are required, but not limited, to turn in the following source files:
Assignment8.java(More code need to be added)
Athlete.java(given by the instructor, it needs to be modified for this assignment)
AthleteNameComparator.java
MedalCountComparator.java
Sorts.java
AthleteManagement.java
Class Diagram:
Athlete
The Athlete class implements the "Serializable" interface so that its object can be stored. (The
Serializable interface is defined in the "java.io" package.)
AthleteNameComparator
The AthleteNameComparator class implements the "Comparator" interface (The Comparator
interface is in "java.util" package.). It needs to define the following method that was an
inherited abstract method from Comparator interface:
public int compare(Object first, Object second)
(Note that you can also define:
public int compare(Athlete first, Athlete second)
instead by making the class implements Comparator.
If the first argument object has a last name lexicographically less than that of the second
argument, an int less than zero is returned. If the first argument object has a last name
lexicographically larger than that of the second argument, an int greater than zero is returned. If
their last names are same, then their first names should be compared. If they have same first and
last names, then 0 should be returned.
MedalCountComparator
The MedalCountComparator class implements the "Comparator" interface (The Comparator
interface is in "java.util" package.). It needs to define the following method that was an
inherited abstract method from Comparator interface:
public int compare(Object first, Object second)
(Note that you can also define:
public int compare(Athlete first, Athlete second)
instead by making the class implements Comparator.
If the first argument object has a larger gold medal count than that of the second argument, an int
less than zero is returned. If the first argument object has a smaller gold medal count than that of
the second argument, an int greater than zero is returned. If both gold medal counts are same,
2. then their silver medal counts should be compared. If both gold medal counts are same and also
silver medal counts are same, then their bronze counts should be compared. If all of gold, silver,
and bronze medal counts are same, then 0 should be returned.
Sorts
The Sorts class is a utility class that will be used to sort a list of Athlete objects. Sorting
algorithms are described in the algorithm note posted under Notes section of the course web site.
These algorithms sort numbers stored in an array. It is your job to modify it to sort objects stored
in an array list (or a vector).
The Sorts class object will never be instantiated. It must have the following methods:
public static void sort(ArrayList objects, Comparator)
Your sort method utilizes the compare method of the parameter Comparator object to sort. You
can use one of Selection sort or Insertion Sort.
AthleteManagement
The AthleteManagement class has a list of Athlete objects that can be organized at the athlete
management system. The athlete management system will be a fully encapsulated object. The
AthleteManagement class implements the Serializable interface.
It has the following attributes:
The following public methods should be provided to interact with the athlete management
system:
No input/output should occur in the athlete management system. User interaction should be
handled only by the driver class.
You may add other methods to the class in order to make your life easier.
Assignment8
All input and output should be handled in Assignment8 class. The main method should start by
displaying this updated menu in this exact format:
ChoicettAction
------tt------
AttAdd Athlete
DttCount Athletes for Medal Type
EttSearch for Athlete Name
LttList Athletes
OttSort by Athlete Names
PttSort by Medal Counts
QttQuit
RttRemove by Athlete Name
TttClose AthleteManagement
3. UttWrite Text to File
VttRead Text from File
WttSerialize AthleteManagement to File
XttDeserialize AthleteManagement from File
?ttDisplay Help
Next, the following prompt should be displayed:
What action would you like to perform?
Read in the user input and execute the appropriate command. After the execution of each
command, redisplay the prompt. Commands should be accepted in both lowercase and
uppercase. The following commands are modified or new.
Add Athlete
Your program should display the following prompt:
Please enter the following information of an athlete:
First Name:
Read in first name and prompt:
Last Name:
Read in last name and prompt:
Sport:
Read in sport and prompt:
The number of gold medals
Read in a number of gold medals and prompt:
The number of silver medals
Read in a number of silver medals and prompt:
The number of bronze medals
Read in a number of bronze medals, and if the Athlete object with the first and last names is not
in the athlete list, then add it into the athlete list and display:
athlete added
Otherwise, display:
athlete exists
Also, if any number of any medals entered is not an integer, display:
Please enter a numeric value for the number of medals. Athlete not added
Count Athletes By Medal Type
Your program should display the following prompt:
Please enter a medal type, 0 for gold, 1 for silver, 2 for bronze, to count the athletes with such
medal:
Read in a medal type, and count the number of athletes that have at least one medal of the type,
4. and print the number.
Also, if the entered medal type is not an integer, display:
Please enter an integer for a medal type, 0 for gold, 1 for silver, 2 for bronze.
Search for Athlete Name
Your program should display the following prompt:
"Please enter the first and last names of an athlete to search:
"First Name:
Read in the fist name, then display the following prompt:
Last Name:
Read in the last name, and search the athlete list based on these information. If there exists a
Athlete object with the first and last name, then display the following:
athlete found
Otherwise, display this:
athlete not found
Sort By Athlete Names
Your program should sort the athlete list using last names and first names in alphabetical order
by last names first, and if they are same, comparing first names and output the following:
sorted by athlete names
Sort By Medal Counts
Your program should sort the athlete list using their medal counts in decreasing order, sort by
gold medal counts first, then by silver, then by bronze and output the following:
sorted by medal counts
Remove By Athlete Name
Your program should display the following prompt:
Please enter the first and last names of an athlete to remove:
First Name:
Read in the first name and display the following prompt:
Last Name:
Read in the last name. If the Athlete object can be found in the athlete list, then remove it from
the list, and display the following:
athlete removed
If there is no such Athlete object in the athlete list, display:
athlete not found
List Athletes
Each Athlete object information in the athlete list should be displayed using the toString method
provided in the Athlete class. (and use listAthletes( ) method in the AthleteManagement class.)
5. If there is no Athlete object in the athlete list, display:
no athlete
Close AthleteManagement
Delete all Athlete objects. Then, display the following:
athlete management system closed
Write Text to File
Your program should display the following prompt:
Please enter a file name to write:
Read in the filename and create an appropriate object to get ready to read from the file. Then it
should display the following prompts:
Please enter a string to write in the file:
Read in the string that a user types, say "input", then attach " " at the end of the string, and
write it to the file. (i.e. input+" " string will be written in the file.)
If the operation is successful, display the following:
FILENAME was written
Replace FILENAME with the actual name of the file.
Use try and catch statements to catch IOException. The file should be closed in a finally
statement.
Read Text from File
Your program should display the following prompt:
Please enter a file name to read:
Read in the file name create appropriate objects to get ready to read from the file. If the operation
is successful, display the following (replace FILENAME with the actual name of the file):
FILENAME was read
Then read only the first line in the file, and display:
The first line of the file is:
CONTENT
where CONTENT should be replaced by the actual first line in the file.
Your program should catch the exceptions if there are. (Use try and catch statement to catch,
FileNotFoundException, and the rest of IOException.)
If the file name cannot be found, display
FILENAME was not found
where FILENAME is replaced by the actual file name.
Serialize AthleteManagement to File
Your program should display the following prompt:
Please enter a file name to write:
6. Read in the filename and write the serialized AthleteManagement object out to it. Note that any
objects to be stored must implement Serializable interface.The Serializable interface is defined in
java.io.* package. If the operation is successful, display the following:
FILENAME was written
Replace FILENAME with the actual name of the file.
Use try and catch statements to catch NotSerializableExeption and IOException.
Deserialize AthleteManagement from File
Your program should display the following prompt:
Please enter a file name to read:
Read in the file name and attempt to load the AthleteManagement object from that file. Note that
there is only one AthleteManagement object in the Assignment8 class, and the first object read
from the file should be assigned to the AthleteManagement object. If the operation is successful,
display the following (replace FILENAME with the actual name of the file):
FILENAME was read
Your program should catch the exceptions if there are.
(Use try and catch statement to catch ClassNotFoundException, FileNotFoundException, and the
rest of IOException.)
See the output files for exception handling.Attribute nameAttribute
typeDescriptionathleteListArrayList or VectorA list of Athlete objects in the athlete management
system
Solution
Answer:
Complete Code:
//Athlete.java
public class Athlete implements java.io.Serializable
{
private String firstName, lastName;
private String sport;
private int gold, silver, bronze;
//Constructor to initialize all member variables
public Athlete()
{
firstName = "?";
lastName = "?";
7. sport = "?";
gold = 0;
silver = 0;
bronze = 0;
}
//Accessor methods
public String getFirstName()
{
return firstName;
}
public String getLastName()
{
return lastName;
}
public String getSport()
{
return sport;
}
public int getGold()
{
return gold;
}
public int getSilver()
{
return silver;
}
public int getBronze()
{
return bronze;
}
//Mutator methods
public void setFirstName(String first)
{
firstName = first;
}
public void setLastName(String last)
8. {
lastName = last;
}
public void setSport(String someSport)
{
sport = someSport;
}
public void setGold(int count)
{
gold = count;
}
public void setSilver(int count)
{
silver = count;
}
public void setBronze(int count)
{
bronze = count;
}
//toString() method returns a string containg information of an athlete
public String toString()
{
String result = "Name:t" + lastName + "," + firstName + " " + "Sport:t" + sport + "
" + "Medal Count: " + "Gold: " + gold + " "+ "Silver: " + silver + " "+
"Bronze: " + bronze + " ";
return result;
}
}
//AthleteNameComparator.java
import java.io.*;
import java.util.*;
//AthleteNameComparator class
public class AthleteNameComparator implements Comparator
{
//compare first & second Athlete
public int compare(Athlete first, Athlete second)
9. {
//Check last name of first and second Athlete
if(first.getLastName().compareToIgnoreCase(second. getLastName()) < 0)
//if second athlete last name is greater, then //return -1
return -1;
//check last name of first athlete is greter than //second Athlete
else if(first.getLastName(). compareToIgnoreCase(second.getLastName()) > 0)
//if it so, return 1
return 1;
//otherwise
else
//return 0
return 0;
}
}
//MedalCountComparator.java
import java.io.*;
import java.util.*;
//MedalCountComparator class
public class MedalCountComparator implements Comparator
{
//compare first & second athlete by medal count
public int compare(Athlete first, Athlete second)
{
//if first athlete is having more number of gold medals then
if(first.getGold() > second.getGold())
//return -1
return -1;
//if second athlete is having more number of gold medals then
else if(first.getGold() < second.getGold())
//return 1
return 1;
//if none of them have no gold medals
else
{
//if first athlete is having more no. of silver
10. if(first.getSilver() > second.getSilver())
//return -1
return -1;
//if second athlete is having more no. of silver
else if(first.getSilver() < second.getSilver())
//return 1
return 1;
//if none them having silver
else
{
//if first athlete is having more no. of bronze
if(first.getBronze() > second.getBronze())
//return -1
return -1;
//if second athlete is having more no. of bronze
else if(first.getBronze() < second.getBronze())
//return 1
return 1;
//otherwise
else
//return 0
return 0;
}
}
}
}
//Sorts.java
//import the needed header files
import java.util.*;
//Sorts class
public class Sorts
{
//sort method
public static void sort(ArrayList myAthList, Comparator myComp)
{
//for all athletes in the myAthList
11. for(int kk=1;kk0 && myComp.compare(myAthList.get(pp-1),bAth)>=0)
{
//get (pp-1) athlete
Athlete sAth=myAthList.get(pp-1);
//set sAth at pp
myAthList.set(pp, sAth);
//decrement pp
pp--;
}
//set bAth at pp
myAthList.set(pp,bAth);
}
}
}
//AthleteManagement.java
//import the needed files
import java.io.*;
import java.util.*;
import java.lang.*;
//AthleteManagement class
public class AthleteManagement implements Serializable
{
//athleteList
ArrayList athleteList;
//constructor
public AthleteManagement()
{
//instantiate athleteList
athleteList=new ArrayList();
}
//method check if athlete already exist
public int athleteNameExists(String firstName, String lastName)
{
int idd=-1;
//for the athletes in the athleteList
for(Athlete myAth:athleteList)
12. {
//compare firstName and lastName with myAth firstName & lastName
if(myAth.getFirstName().equals(firstName) && myAth.getLastName().equals(lastName))
{
//if matches then return the index of myAth
idd=athleteList.indexOf(myAth);
}
}
//return idd
return idd;
}
//method to return the nunber of athletes for the medalType
public int countHowManyAthletesHaveMedals(int medalType)
{
//intialize medCnt to 0
int medCnt=0;
//for all athletes in the athleteList
for(Athlete myAth:athleteList)
{
//for the medalType
switch(medalType)
{
//for gold
case 0:
//if myAth has gold medals
if(myAth.getGold()>0)
//increment medCnt by 1
medCnt++;
break;
//for silver
case 1:
//if myAth has silver medals
if(myAth.getSilver()>0)
//increment medCnt by 1
medCnt++;
13. break;
//for bronze
case 2:
//if myAth has bronze medals
if(myAth.getBronze()>0)
//increment medCnt by 1
medCnt++;
break;
}
}
//return the medal count medCnt
return medCnt;
}
//method to add the athlete
public boolean addAthlete(String firstName, String lastName, String sport, int gold, int silver, int
bronze) {
//create myAthlete
Athlete myAthlete=new Athlete();
//set firstName
myAthlete.setFirstName(firstName);
//set lastName
myAthlete.setLastName(lastName);
//set sport
myAthlete.setSport(sport);
//set gold medals
myAthlete.setGold(gold);
//set silver medals
myAthlete.setSilver(silver);
//set bronze medals
myAthlete.setBronze(bronze);
//check if myAthlete already exists in athleteList
int exx=athleteNameExists(firstName, lastName);
//if exist
if(exx!=-1)
{
//no need to add myAthlete once again. so return false
14. return false;
}
//otherwise add myAthlete
else
{
//add myAthlete to athleteList
athleteList.add(myAthlete);
//return true
return true;
}
}
//method to remove athlete by firstName & lastName
public boolean removeAthleteByName(String firstName, String lastName)
{
//check if athlete with firstName & lastName exist
int exx=athleteNameExists(firstName, lastName);
//if exist
if(exx!=-1)
{
//remove athlete by exx
athleteList.remove(exx);
//return true
return true;
}
//if athlete doesnot exist
else
{
//return false
return false;
}
}
//method to sort the athlete by name
public void sortByAthleteNames()
{
//call sort method to sort athleteList
Sorts.sort(athleteList, new AthleteNameComparator());
15. }
//method to sort the athlete by medal counts
public void sortByMedalCounts()
{
//call sort method to sort athleteList
Sorts.sort(athleteList, new MedalCountComparator());
}
//method return the list of athletes in the athleteList
public String listAthletes()
{
String myStrr="";
//if athleteList has athlete
if(athleteList.size()>=1)
{
//for all athletes
for(int kk=0;kk -1)
System.out.print("athlete found ");
else
System.out.print("athlete not found ");
break;
case 'L': //List athletes
System.out.print(athleteRecord1.listAthletes());
break;
case 'O': // Sort by athlete names
athleteRecord1.sortByAthleteNames();
System.out.print("sorted by athlete names ");
break;
case 'P': // Sort by medal counts
athleteRecord1.sortByMedalCounts();
System.out.print("sorted by medal counts ");
break;
case 'Q': //Quit
break;
case 'R': //Remove by athlete names
System.out.print("Please enter the first and last names of an athlete to remove: ");
System.out.print("First Name: ");
16. firstName = stdin.readLine().trim();
System.out.print("Last Name: ");
lastName = stdin.readLine().trim();
operation =athleteRecord1. removeAthleteByName(firstName, lastName);
if (operation == true)
System.out.print("athlete removed ");
else
System.out.print("athlete not found ");
break;
case 'T': //Close AthleteManagement
athleteRecord1.closeAthleteManagement();
System.out.print("athlete management system closed ");
break;
case 'U': //Write Text to a File
System.out.print("Please enter a file name to write: ");
filename = stdin.readLine().trim();
try
{
BufferedWriter bb=new BufferedWriter(new FileWriter(filename));
System.out.println("Enter a line to write to the file:");
String inpp=stdin.readLine();
bb.write(inpp);
bb.newLine();
bb.close();
}
catch(FileNotFoundException exxpp)
{
exxpp.printStackTrace();
}
catch(IOException exxpp)
{
exxpp.printStackTrace();
}
break;
case 'V': //Read Text from a File
System.out.print("Please enter a file name to read: ");
17. filename = stdin.readLine().trim();
try
{
BufferedReader bb=new BufferedReader(new FileReader(filename));
String frstLne=bb.readLine();
System.out.println(filename+" was read ");
System.out.println("The first line of the file is : ");
System.out.println(frstLne+" ");
bb.close();
}
catch(FileNotFoundException exxpp)
{
exxpp.printStackTrace();
}
catch(IOException exxpp)
{
exxpp.printStackTrace();
}
break;
case 'W': //Serialize ProjectManagement to a File
System.out.print("Please enter a file name to write: ");
filename = stdin.readLine().trim();
try
{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(filename));
oos.writeObject(athleteRecord1);
System.out.println(filename+" was written");
oos.close();
}
catch(FileNotFoundException exxpp)
{
exxpp.printStackTrace();
}
catch(IOException exxpp)
{
exxpp.printStackTrace();
18. }
break;
case 'X': //Deserialize ProjectManagement from a File
System.out.print("Please enter a file name to read: ");
filename = stdin.readLine().trim();
try
{
ObjectInputStream ois= new ObjectInputStream (new FileInputStream(filename));
athleteRecord1= (AthleteManagement)ois.readObject();
System.out.println(filename+" was read");
ois.close();
}
catch(ClassNotFoundException exxpp)
{
exxpp.printStackTrace();
}
catch(FileNotFoundException exxpp)
{
exxpp.printStackTrace();
}
catch(IOException exxpp)
{
exxpp.printStackTrace();
}
break;
case '?': //Display Menu
printMenu();
break;
default:
System.out.print("Unknown action ");
break;
}
}
else
{
System.out.print("Unknown action ");
19. }
} while (input1 != 'Q' || line.length() != 1);
}
catch (IOException exception)
{
System.out.print("IO Exception ");
}
}
/** The method printMenu displays the menu to a user **/
public static void printMenu()
{
System.out.print("ChoicettAction " +
"------tt------ " +
"AttAdd Athlete " +
"DttCount Athletes for Medal Type " +
"EttSearch for Athlete Name " +
"LttList Athletes " +
"OttSort by Athlete Names " +
"PttSort by Medal Counts " +
"QttQuit " +
"RttRemove by Athlete Name " +
"TttClose AthleteManagement " +
"UttWrite Text to File " +
"VttRead Text from File " +
"WttSerialize AthleteManagement to File " +
"XttDeserialize AthleteManagement from File " +
"?ttDisplay Help ");
}
} // end of Assignment8 class
run:
Choice Action
------ ------
A Add Athlete
D Count Athletes for Medal Type
E Search for Athlete Name
L List Athletes
20. O Sort by Athlete Names
P Sort by Medal Counts
Q Quit
R Remove by Athlete Name
T Close AthleteManagement
U Write Text to File
V Read Text from File
W Serialize AthleteManagement to File
X Deserialize AthleteManagement from File
? Display Help
What action would you like to perform?
A
Please enter the following information of an athlete:
First Name:
David
Last Name:
Cameron
Sport:
Swimming
The number of gold medals
4
The number of silver medals
2
The number of bronze medals
1
athlete added
What action would you like to perform?
A
Please enter the following information of an athlete:
First Name:
David
Last Name:
Michal
Sport:
Boxing
The number of gold medals
21. 5
The number of silver medals
4
The number of bronze medals
9
athlete added
What action would you like to perform?
D
Please enter a medal type, 0 for gold, 1 for silver, 2 for bronze, to count the athletes with such
medal:
2
The number of athletes with the given medal type: 2
What action would you like to perform?
L
Name: Cameron,David
Sport: Swimming
Medal Count:
Gold: 4
Silver: 2
Bronze: 1
Name: Michal,David
Sport: Boxing
Medal Count:
Gold: 5
Silver: 4
Bronze: 9
What action would you like to perform?
O
sorted by athlete names
What action would you like to perform?
L
Name: Cameron,David
Sport: Swimming
Medal Count:
Gold: 4
Silver: 2
22. Bronze: 1
Name: Michal,David
Sport: Boxing
Medal Count:
Gold: 5
Silver: 4
Bronze: 9
What action would you like to perform?
P
sorted by medal counts
What action would you like to perform?
L
Name: Michal,David
Sport: Boxing
Medal Count:
Gold: 5
Silver: 4
Bronze: 9
Name: Cameron,David
Sport: Swimming
Medal Count:
Gold: 4
Silver: 2
Bronze: 1
What action would you like to perform?Q