Question

For this project you will write a Java program that produces a simple formatted report. You...

For this project you will write a Java program that produces a simple formatted report. You will prompt the user for the name of a file that is in this format:

Rory Williams
88
92
78
-1
James Barnes
87
76
91
54
66
-1
Sarah-Jane Smith
92
86
95
85
82
-1
Jack Sparrow
18
54
13
0
-1

And produce a formatted report to another file that looks like this:

Name                 Mean Median Max Min
-------------------- ---- ------ --- ---
Rory Williams          86     88  92  78
James Barnes           74     76  91  54
Sarah-Jane Smith       88     86  95  82
Jack Sparrow           21     15  54   0

Total number of participants: 4
Highest average score: Sarah Jane Smith (88)
Lowest average score: Jack Sparrow (21)

The first file shows a list of scores for players in some kind of online game. The file is formatted so that each player first has their name (First Last) on a line followed by a list of scores each on a line by itself. The list of scores for a player ends with a negative number, and the information for the next player starts on the line after that.

To build this program you will first complete a class that will let you create objects to hold the various statistics about the players stored in the file. Then you will write various methods to let you use your PlayerScores objects to read information from the file and write it to a formatted report.

You will need to create two class files for this project. First create a project and create a new class in that project named PlayerScores, then paste in the skeleton below into your class:

/**
 * A simple class to hold player information for reporting.
 * 
 * @author YOUR NAME HERE
 * @version DATE HERE
 */

import java.util.ArrayList;
import java.util.List;

public class PlayerScores {

    /**
     * Private member variables to hold the player's name and stats.
     */
    private String firstName;
    private String lastName;
    private List<Integer> scores;

    /**
     * Constructor for the PlayerScores class. MUST assign values to all of the
     * private member variables.
     *
     * @param firstName
     *            first name of player
     * @param lastName
     *            last name of player
     */
    public PlayerScores(String firstName, String lastName) {
        // NOTE: This constructor has already been written for you.

        this.firstName = firstName;
        this.lastName = lastName;
        this.scores = new ArrayList<Integer>();
    }

    /**
     * Adds a score to a players list of scores
     *
     * @param score
     *            the score to be added
     */
    public void addScore(int score) {
        // NOTE: This procedure has already been written for you.

        this.scores.add(score);
    }

    /**
     * Computes the integer average of the player's list of scores.
     *
     * @return the integer average score for the player. Zero if the player has
     *         no scores.
     */
    public int getAverage() {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return 0;
    }

    /**
     * Computes the integer median of the player's list of scores.
     *
     * @return the integer median score for the player. Zero if the player has
     *         no scores.
     */
    public int getMedian() {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return 0;
    }

    /**
     * Determines the maximum score the player has received
     *
     * @return the maximum score for the player. Zero if the player has no
     *         scores.
     */
    public int getMax() {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return 0;
    }

    /**
     * Determines the minimum score the player has received.
     *
     * @return the minimum score for the player. Zero if the player has no
     *         scores.
     */
    public int getMin() {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return 0;
    }

    /**
     * Returns the name of the player in firstName lastName format.
     *
     * @return the name of the player.
     */
    public String getName() {
        // NOTE: This function has already been completed for you.

        return this.firstName + " " + this.lastName;
    }

}

Next create a class named FormattedReport in the same project folder and paste in the skeleton below:

/**
 * Prompts the user for a filename of player score information and produces
 * a formatted report summarizing that information.
 *
 * @author YOUR NAME HERE
 * @version DATE HERE
 */

import java.io.PrintWriter;
import java.util.List;
import java.util.Scanner;

public class FormattedReport {

    /**
     * Displays the message "promptMsg" to the user and reads the next full line
     * that the user enters. If the user enters an empty string, reports the
     * error message "ERROR! Input value cannot be empty!" and then loops,
     * repeatedly prompting them with "promptMsg" to enter a new string until
     * the user enters a non-empty String
     *
     * @param in
     *            Scanner to read user input from
     * @param promptMsg
     *            Message to display to user to prompt them for input
     * @return the String entered by the user
     */
    public static String promptForNonEmptyString(Scanner in, String promptMsg) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.

        return "";
    }

    /**
     * Given a Scanner as input read in a player name, followed by a list of
     * integers one at time until a negative value is read from the Scanner. The
     * player name and the scores read from the file are used to create a
     * PlayerScores object which is returned by this method. You may assume that
     * the file format is good for this method (i.e. the first line will be a
     * name in Firstname Lastname format with 0 or more integers on the lines
     * below it and a negative value to end the set of scores.
     *
     * @param inScanner
     *            the Scanner to read the player info from
     * @return a PlayerScores object for the player read from the Scanner
     */
    public static PlayerScores readNextScoreset(Scanner inScanner) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return new PlayerScores("", "");
    }

    /**
     * Given a list of PlayerScores objects, return the object representing the
     * player who has the highest average score. In the case of a tie, return
     * the first player with that score in the list.
     *
     * @param players
     *            list of players to search through
     * @return PlayerScores object representing the player with the highest
     *         average score
     */
    public static PlayerScores findHighestScorer(List<PlayerScores> players) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return new PlayerScores("", "");
    }

    /**
     * Given a list of PlayerScores objects, return the object representing the
     * player who has the lowest average score. In the case of a tie, return the
     * first player with that score in the list.
     *
     * @param players
     *            list of players to search through
     * @return PlayerScores object representing the player with the highest
     *         average score
     */
    public static PlayerScores findLowestScorer(List<PlayerScores> players) {
        // TODO - complete this function

        // TODO - the following line is only here to allow this program to
        //  compile.  Replace it and remove this comment when you complete
        //  this method.
        return new PlayerScores("", "");
    }

    /**
     * Given a PrintWriter named report, prints the header of the report (i.e.
     * the first two lines showing column names and the lines underneath).
     *
     * @param report
     *            the PrintWriter stream to write the report to
     */
    public static void printReportHeader(PrintWriter report) {
        // NOTE: This procedure has been completed for you
        report.println("Name                 Mean Median Max Min");
        report.println("-------------------- ---- ------ --- ---");
    }

    /**
     * Given a PrintWriter named report and a PlayerScores object, prints the
     * single line of the report that represents the "stats" for that player.
     *
     * @param report
     *            the PrintWriter stream to write the report to
     * @param player
     *            the player information to write to the report
     */
    public static void printReportLine(PrintWriter report, PlayerScores player) {
        // TODO - complete this procedure

    }

    /**
     * Given a PrintWriter named report and a List of PlayerScores objects,
     * prints the summary lines of the report indicating the total number of
     * participants, the player with the highest score and the player with the
     * lowest score (see assignment specification for report details).
     *
     * @param report
     *            the PrintWriter stream to write the report to
     * @param players
     *            the list of players to summarize
     */
    public static void printReportSummary(PrintWriter report, List<PlayerScores> players) {
        // NOTE: This procedure has been completed for you.  If you have
        // correctly implemented the methods in PlayerScores and
        // in this project, this summary should work.
        report.println();
        report.println("Total number of participants: " + players.size());
        PlayerScores highest = findHighestScorer(players);
        report.println("Highest average score: " + highest.getName() + " ("
                + highest.getAverage() + ")");
        PlayerScores lowest = findLowestScorer(players);
        report.println("Lowest average score: " + lowest.getName() + " ("
                + lowest.getAverage() + ")");
    }

    public static void main(String[] args) {
        // TODO - complete this procedure
    }
}

Your job is to complete the missing methods in the PlayerScores class as well as in the FormattedReport class. When you run the FormattedReport class, you should be able to produce the following transcript (remember - items in BOLD are user input):

Enter an input file name: playerStats.txt
Enter an output file name: playerReport.txt

If the file with the player information is saved in your project folder under the name "playerStats.txt", then this transcript should produce a file named "playerReport.txt" that has the same report quoted above in it. Note that if the user enters a blank line for either of these your program MUST loop until they enter something other than an empty line. (The method promptForNonEmptyString can help you with this requirement). Also note that for full credit your program MUST implement all file I/O in a try-catch block.

NOTE 1: We discussed an algorithm for computing the median of a list of numbers in class. As a reminder, you can use the following method to compute the median of a List:

  • Sort the List
  • If the List length is odd, the median is element at the index in the middle of the list
  • if the List length is even, the median is the average of the two elements at the indices in the middle of the list

NOTE 2: To get the columns to line up nicely, using the format method on the PrintWriter class. There are lecture notes on Carmen on how to use format, and you can also view this quick tutorial from Oracle on Oracle's Java website.

NOTE 3 For this project you are only being provided individual test cases for the methods in the PlayerScores class. It is up to you to adequately test the methods in the FormattedReport class for yourself. Note that there are two test cases below dealing with the output of the FormattedReport class - one that will check the output to the screen and one that will check the output made to your report file. Also note that some of the methods are provided for you in both the FormattedReport and PlayerScores classes - you should not need to make any changes to those methods to get your code to produce the correct transcripts.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

//Java

/**
 * A simple class to hold player information for reporting.
 *
 * @author YOUR NAME HERE
 * @version DATE HERE
 */

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class PlayerScores {

    /**
     * Private member variables to hold the player's name and stats.
     */
    private String firstName;
    private String lastName;
    private List<Integer> scores;

    /**
     * Constructor for the PlayerScores class. MUST assign values to all of the
     * private member variables.
     *
     * @param firstName
     *            first name of player
     * @param lastName
     *            last name of player
     */
    public PlayerScores(String firstName, String lastName) {
        // NOTE: This constructor has already been written for you.

        this.firstName = firstName;
        this.lastName = lastName;
        this.scores = new ArrayList<Integer>();
    }

    /**
     * Adds a score to a players list of scores
     *
     * @param score
     *            the score to be added
     */
    public void addScore(int score) {
        // NOTE: This procedure has already been written for you.

        this.scores.add(score);
    }

    /**
     * Computes the integer average of the player's list of scores.
     *
     * @return the integer average score for the player. Zero if the player has
     *         no scores.
     */
    public int getAverage() {
        if(scores.size()==0)
        return 0;
        else
        {
            Integer total =0;
            for (Integer i:scores
                 ) {
                total+=i;
            }
            total = total/scores.size();
            return total;
        }
    }

    /**
     * Computes the integer median of the player's list of scores.
     *
     * @return the integer median score for the player. Zero if the player has
     *         no scores.
     */
    public int getMedian() {
        //sort the list
        Collections.sort(scores);
        int middle  = scores.size()/2;
        //if list length is odd
        if(scores.size()%2!=0)
        {
            return scores.get(middle);
        }
        //if list length is even
        else
        {
            return (scores.get(middle-1)+scores.get(middle))/2;
        }
    }

    /**
     * Determines the maximum score the player has received
     *
     * @return the maximum score for the player. Zero if the player has no
     *         scores.
     */
    public int getMax() {
        int max = scores.get(0);
        for (int i = 0; i < scores.size(); i++) {
            if(max<scores.get(i))
                max= scores.get(i);
        }
        return max;
    }

    /**
     * Determines the minimum score the player has received.
     *
     * @return the minimum score for the player. Zero if the player has no
     *         scores.
     */
    public int getMin() {
        int min = scores.get(0);
        for (int i = 0; i < scores.size(); i++) {
            if(min >scores.get(i))
                min = scores.get(i);
        }
        return min;
    }

    /**
     * Returns the name of the player in firstName lastName format.
     *
     * @return the name of the player.
     */
    public String getName() {
        // NOTE: This function has already been completed for you.

        return this.firstName + " " + this.lastName;
    }

}

//==========================================

/**
 * Prompts the user for a filename of player score information and produces
 * a formatted report summarizing that information.
 *
 * @author YOUR NAME HERE
 * @version DATE HERE
 */

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class FormattedReport {

    /**
     * Displays the message "promptMsg" to the user and reads the next full line
     * that the user enters. If the user enters an empty string, reports the
     * error message "ERROR! Input value cannot be empty!" and then loops,
     * repeatedly prompting them with "promptMsg" to enter a new string until
     * the user enters a non-empty String
     *
     * @param in
     *            Scanner to read user input from
     * @param promptMsg
     *            Message to display to user to prompt them for input
     * @return the String entered by the user
     */
    public static String promptForNonEmptyString(Scanner in, String promptMsg) {
        System.out.print(promptMsg);
        String input = in.nextLine();
        while (input.equals(""))
        {
            System.out.println("ERROR! Input value cannot be empty!");
            System.out.print(promptMsg);
            input = in.nextLine();
        }

        return input;
    }

    /**
     * Given a Scanner as input read in a player name, followed by a list of
     * integers one at time until a negative value is read from the Scanner. The
     * player name and the scores read from the file are used to create a
     * PlayerScores object which is returned by this method. You may assume that
     * the file format is good for this method (i.e. the first line will be a
     * name in Firstname Lastname format with 0 or more integers on the lines
     * below it and a negative value to end the set of scores.
     *
     * @param inScanner
     *            the Scanner to read the player info from
     * @return a PlayerScores object for the player read from the Scanner
     */
    public static PlayerScores readNextScoreset(Scanner inScanner) {
        String firstName="",lastName="";
        int score=0;
        PlayerScores playerScores=null;
        firstName = inScanner.next();
        lastName = inScanner.next();
        playerScores = new PlayerScores(firstName,lastName);
            while (inScanner.hasNext())
                  {
                      score = inScanner.nextInt();
                      if (score==-1)
                          break;
                      else
                      {
                          playerScores.addScore(score);
                      }

                  }

        return playerScores;
    }

    /**
     * Given a list of PlayerScores objects, return the object representing the
     * player who has the highest average score. In the case of a tie, return
     * the first player with that score in the list.
     *
     * @param players
     *            list of players to search through
     * @return PlayerScores object representing the player with the highest
     *         average score
     */
    public static PlayerScores findHighestScorer(List<PlayerScores> players) {
            int maxIndex=-1,max=0;
        for (int i = 0; i <players.size() ; i++) {
            if(max < players.get(i).getAverage())
            {
                max = players.get(i).getAverage();
                maxIndex =i;
            }
        }
        return players.get(maxIndex);
    }

    /**
     * Given a list of PlayerScores objects, return the object representing the
     * player who has the lowest average score. In the case of a tie, return the
     * first player with that score in the list.
     *
     * @param players
     *            list of players to search through
     * @return PlayerScores object representing the player with the highest
     *         average score
     */
    public static PlayerScores findLowestScorer(List<PlayerScores> players) {
        int minIndex =-1, min =players.get(0).getAverage();
        for (int i = 0; i <players.size() ; i++) {
            if(min > players.get(i).getAverage())
            {
                min = players.get(i).getAverage();
                minIndex =i;
            }
        }
        return players.get(minIndex);

    }

    /**
     * Given a PrintWriter named report, prints the header of the report (i.e.
     * the first two lines showing column names and the lines underneath).
     *
     * @param report
     *            the PrintWriter stream to write the report to
     */
    public static void printReportHeader(PrintWriter report) {
        // NOTE: This procedure has been completed for you
        report.println("Name                 Mean Median Max Min");
        report.println("-------------------- ---- ------ --- ---");
    }

    /**
     * Given a PrintWriter named report and a PlayerScores object, prints the
     * single line of the report that represents the "stats" for that player.
     *
     * @param report
     *            the PrintWriter stream to write the report to
     * @param player
     *            the player information to write to the report
     */
    public static void printReportLine(PrintWriter report, PlayerScores player) {
        report.println(player.getName()+" "+player.getAverage()+" "+player.getMedian()+" "+player.getMax()+" "+player.getMin());

    }

    /**
     * Given a PrintWriter named report and a List of PlayerScores objects,
     * prints the summary lines of the report indicating the total number of
     * participants, the player with the highest score and the player with the
     * lowest score (see assignment specification for report details).
     *
     * @param report
     *            the PrintWriter stream to write the report to
     * @param players
     *            the list of players to summarize
     */
    public static void printReportSummary(PrintWriter report, List<PlayerScores> players) {
        // NOTE: This procedure has been completed for you.  If you have
        // correctly implemented the methods in PlayerScores and
        // in this project, this summary should work.
        report.println();
        report.println("Total number of participants: " + players.size());
        PlayerScores highest = findHighestScorer(players);
        report.println("Highest average score: " + highest.getName() + " ("
                + highest.getAverage() + ")");
        PlayerScores lowest = findLowestScorer(players);
        report.println("Lowest average score: " + lowest.getName() + " ("
                + lowest.getAverage() + ")");
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String inputFileNAme=promptForNonEmptyString(in,"Enter input File Name: ");
        String outputFileNAme=promptForNonEmptyString(in,"Enter output File Name: ");
        Scanner inFile=null;
        PrintWriter outFile=null;
        //List Of Players
        ArrayList<PlayerScores> playerScores = new ArrayList<>();
        try
        {
            inFile = new Scanner(new File(inputFileNAme));
            outFile = new PrintWriter(new FileWriter(outputFileNAme));
            printReportHeader(outFile);
            while (inFile.hasNext())
            {
                PlayerScores playerScore = readNextScoreset(inFile);
                playerScores.add(playerScore);
                //write to file
                printReportLine(outFile,playerScore);
            }
            printReportSummary(outFile,playerScores);
            //Player with highest score
            PlayerScores playerScores1 = findHighestScorer(playerScores);
            //Player with lowest score
            PlayerScores playerScores2 = findLowestScorer(playerScores);

        }
        catch (IOException e)
        {
            System.err.println(e);
        }
        finally {
            inFile.close();
            outFile.close();
        }
    }
}

//input file

//Output

// If you need any help regarding this solution ...... please leave a comment ....... thanks..

Add a comment
Know the answer?
Add Answer to:
For this project you will write a Java program that produces a simple formatted report. You...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT