hi guys, im in my first few weeks of working with java, and am finding it hard to complete an excercise i've been given. We are working with a java program that works over 3 files, and we have to "fill in the blanks".
trouble is, i don't know what is really needed as far as methods and constructors go, and don't really understand the assignment.
The program is supposed to work processing sporting results. We are given a driver program which accepts the user input. this is it:
(LeagueDriver.java)
import java.io.*;
public class LeagueDriver {
private static final char OPTION_ADD = 'a';
private static final char OPTION_PRINT = 'p';
private static final char OPTION_SORT = 's';
private static final char OPTION_FIND = 'f';
private static final char OPTION_QUIT = 'q';
/**
The BufferedReader object is an instance variable, so can be used by any method requiring input from console.
It is necessary to do it this way, otherwise redirection of input (from a file) does not work
*/
private BufferedReader console;
/**
Holds all the data relevant to a League.
Note that the LeagueDriver class doesn't need to know anything about the Team class.
*/
private League theLeague;
/**
Drives the program, namely displays the program's welcome message, and causes the leaugue data to be input,
a menu to be displayed and the users response to be processed.
*/
public static void main(String[] args) throws IOException {
LeagueDriver program = new LeagueDriver(); // created so we can call non-static methods
char response; // users selection from the menu
System.out.println("The League Table Program\n\n");
program.setupLeague();
response = program.displayMenu();
// the logic of the loop is kept in main, and not 'hidden' in another method
while (response != OPTION_QUIT) {
program.processSelection(response);
response = program.displayMenu();
}
System.out.println("Goodbye");
}
/**
The instance variable theLeague will be initialised in setupLeague().
*/
public LeagueDriver() {
console = new BufferedReader(new InputStreamReader(System.in));
}
/**
Gets data from the user so the League object can be instantiated.
*/
private void setupLeague() throws IOException {
String leagueName;
int premiershipPoints;
int numberOfTeams;
String[] namesOfTeams;
System.out.println("League setup\n"
+"------------");
System.out.print("What is the name of this league: ");
leagueName = console.readLine();
System.out.print("How many premiership points is a win worth: ");
premiershipPoints = Integer.parseInt(console.readLine());
System.out.print("How many teams in this league: ");
numberOfTeams = Integer.parseInt(console.readLine());
namesOfTeams = new String[numberOfTeams];
System.out.println("\nPlease enter the team names");
for (int i = 0; i < namesOfTeams.length; i++) {
System.out.print("\tTeam "+ (i+1) +": ");
namesOfTeams[i] = console.readLine();
}
// instantiate the League object
theLeague = new League(leagueName, namesOfTeams, premiershipPoints);
// these statements check that data is stored correctly
System.out.println("The setup for " +theLeague.getName() +" is complete");
System.out.println(leagueName +" has " +theLeague.numberOfTeams() +" teams.");
System.out.println("\nThe league table currently looks like this:");
System.out.println(theLeague);
}
/**
Displays a textual menu
@return user's menu selection (as a lower case character)
*/
private char displayMenu() throws IOException {
System.out.println("\n\nLeague Table Menu\n"
+"-----------------");
System.out.println(OPTION_ADD +" = add game stats");
System.out.println(OPTION_PRINT +" = print table");
System.out.println(OPTION_SORT +" = sort table");
System.out.println(OPTION_FIND +" = find a team");
System.out.println(OPTION_QUIT +" = program");
System.out.print("Please enter an option: ");
return Character.toLowerCase(console.readLine().charAt(0));
}
/**
Depending on the user's selection, invokes different League methods.
Notice how this class is handling all of the user input, and the input is sent to League.
@param selection user's menu selection
*/
private void processSelection(char selection) throws IOException {
switch (selection) {
case OPTION_ADD:
// need more data from user, so go to a method in this class first
addGameStats();
break;
case OPTION_PRINT:
// prints the league ladder (automatically invokes League's toString())
System.out.println(theLeague);
break;
case OPTION_SORT:
// sort the ladder according to the rules dictated by League
theLeague.sortLadder();
break;
case OPTION_FIND:
// prompt & get a team name as a string, then display that team's data
System.out.print("Please enter team name to find: ");
System.out.println(theLeague.findTeam(console.readLine()));
break;
default:
System.out.println("Error: invalid menu option.");
break;
}
}
/**
Gather data for a match before invoking the League method
*/
private void addGameStats() throws IOException {
String team1;
String team2;
int scoreFor;
int scoreAgainst;
System.out.print("Team 1: ");
team1 = console.readLine();
System.out.print("Team 2: ");
team2 = console.readLine();
System.out.print(team1 +"'s score: ");
scoreFor = Integer.parseInt(console.readLine());
System.out.print(team2 +"'s score: ");
scoreAgainst = Integer.parseInt(console.readLine());
theLeague.addGameStats(team1, team2, scoreFor, scoreAgainst);
}
}
this doesn't need changing, but it (probably) will help you guys decipher this. Here are the remaining files.
(League.java)
import java.util.Arrays;
/**
This class does not do any user input!
@version 2.0 5 May 2005
@author YOUR NAME
*/
public class League {
private final int WIN_POINTS;
private String leagueName;
private Team[] teams;
/**
Constructor instantiates the Team array <code>teams</code>, and for each
array element it instantiates a Team object (using the appropriate value
from <code>teamNames</code>).
@param leagueName name of this league
@param teamNames an array of team names
@param pointsForWin number of premiership points a win is worth (assumes a draw is pointsForWin/2)
*/
public League(String leagueName, String[] teamNames, int pointsForWin) {
this.leagueName = leagueName;
teams = new Team[teamNames.length];
// PUT A LOOP HERE TO CREATE A NEW TEAM, 1 FOR EACH NAME IN teamNames
WIN_POINTS = pointsForWin;
}
public String getName() {
return leagueName;
}
public int numberOfTeams() {
return teams.length;
}
/**
Adds the new game stats to the correct 2 teams.
It must update the points for and against to both teams
@param team1 the home team
@param team2 the away team
@param pointsTeam1 the points scored by the home team
@param pointsTeam2 the points scored by the away team
@see #findTeamIndex(java.lang.String)
*/
public void addGameStats(String team1, String team2, int pointsTeam1, int pointsTeam2) {
// YOU MUST COMPLETE THIS METHOD
// hint: make use of the method findTeamIndex
}
/**
Sorts the ladder according to the "natural order" of Teams.
Disaplys a message if the sorting is not performed (e.g. you haven't implemented this method).
Refer to the API for the pre-defined class Arrays.
*/
public void sortLadder() {
// YOU MUST COMPLETE THIS METHOD
// hint: it's one short statement
}
/**
Prints the ladder to the console. Obviously prints info for each team in the array.
Must take advantage of a Team object's <code>toString</code> method.
@see Team#toString
*/
public String toString() {
String str = "\n";
String spacer1 = " ";
str += leagueName.toUpperCase() +" LADDER\n";
str += "\t" + spacer1 + "P\tW\tL\tD\tF\tA\t%\tTotal\n";
for (int i = 0; i < teams.length; i++) {
str += (i+1) + "\t";
// YOU MUST COMPLETE THIS METHOD
}
return str;
}
/**
Each win is worth WIN_POINTS and each draw is worth WIN_POINTS/2
*/
private int calculateTotalPremiershipPoints(Team team) {
return team.getWins() * WIN_POINTS + team.getDraws() * WIN_POINTS/2;
}
public String findTeam(String teamName) {
String str = "";
int index = findTeamIndex(teamName);
if (index < teams.length)
str = teams[index].toString();
else
str = "Error: no team found with the name " +teamName;
return str;
}
/**
Find where in the array the Team with <code>teamName</code> is. Creates a temporary Team to
represent the team we're trying to find so that we can use Team's equals method.
@param teamName the String value used to find the correct <code>teams</code> subscript
@return the array subscript of the <code>teams</code> element that refers to
the Team object which has <code>teamName</code> as an attribute.
If no match, then returns teams.length
*/
private int findTeamIndex(String teamName) {
Team temp = new Team(teamName);
boolean found = false;
int i = 0;
while (i < teams.length && !found) {
if (teams[i].equals(temp)) {
found = true;
}
else
i++;
}
return i;
}
}
That's the second file, i have added all the lines that i know will work, but my attempts at method and constructor making are embarrassingly wrong.
(Team.java)
public class Team implements Comparable {
// implement this class according to the published class diagram solution
// deviating from the design (either fewer or more attributes/methods) will
// result in loss of marks
public Team(String name) {
// COMPLETE THIS CONSTRUCTOR
}
// ADD ACCESSOR METHODS AND THE 1 MUTATOR METHOD
/**
Updates this team's total points for, total points against,
and this team's wins, loses, or draws, as appropriate.
@param pointsFor the points this team scored in a game
@param pointsAgainst the points the opposing team scored against this team
*/
public void updateStats(int pointsFor, int pointsAgainst) {
// YOU MUST COMPLETE THIS METHOD
}
/**
Calculates the ratio of points for to points against, as a percentage of points against.
@return the percentage of points scored against this team, rounded to 2 decimal points.
*/
public double calculatePercentage() {
double percentage;
percentage = (double)getTotalPointsFor() / (double)getTotalPointsAgainst();
percentage *= 10000.0;
percentage = (int)percentage;
percentage /= 100.0;
return percentage;
}
/**
Creates a description of this team. The description consists of
<ul>
<li>team name
<li>number of games played
<li>wins
<li>loses
<li>draws
<li>total points for
<li>total points against
</ul>
Note that it does not concatenate the percentage to this description.<p>
There are always 20 characters from the first letter of the team name,
to the games played digit. Two examples:
<pre>
Adelaide 1 0 1 0 123 132
Port Adelaide 1 1 0 0 132 123
</pre>
*/
public String toString() {
String spacer1 = " ";
return getName() + spacer1.substring(getName().length())
+ (getWins() + getLoses() + getDraws())
+ "\t" + getWins()
+ "\t" + getLoses()
+ "\t" + getDraws()
+ "\t" + getTotalPointsFor()
+ "\t" + getTotalPointsAgainst();
}
/**
2 Team objects are considered equal if they have the same name.
*/
public boolean equals(Object o) {
boolean result = false;
if (o instanceof Team) {
Team other = (Team)o;
result = this.name.equalsIgnoreCase(other.getName());
}
return result;
}
/**
The "natural order" for a team is descending order of wins, percentage, points for, then ascending name.
*/
public int compareTo(Object o) {
int result;
Team other = (Team)o;
result = (other.getWins()+other.getDraws()) - (this.wins+this.draws);
if (result == 0) {
result = other.getWins() - this.wins;
if (result == 0 ) {
result = (int)(other.calculatePercentage()*100) - (int)(this.calculatePercentage()*100);
if (result == 0) {
result = other.getTotalPointsFor() - this.totalPointsFor;
if (result == 0)
result = this.name.compareTo(other.getName());
}
}
}
return result;
}
}
Any pieces of code i try and put in just get me nowhere, because the very Key elements of the program are missing, i am very lost. Please Help?
Thanking you all in advance....
SunshineBusride.