Question

Write a class that encapsulates the concept of a baseball player with the important attributes (name,...

Write a class that encapsulates the concept of a baseball player with the important attributes (name, position, hits, at bats, batting average). The class will have the following methods:

  • Two constructors (a default and a constructor with all parameters)
  • Accessors, mutators, toString, and equals methods
  • The batting average property will not have a public setter, it will be updated any time the hits and/or at bats is set. The getter will round to three digits (.315 or .276, etc.)
  • All properties will be validated
  • The player position will be an enumeration

Your driver will use a 9 element array to represent a baseball team (do not use an ArrayList). Your driver should initialize the array with 9 valid baseball player objects.

  • List the batting average for each player
  • Calculate and display the total number of hits for the team
  • List the players with a batting average of .300 or greater
  • Sort the players based on batting average and list the players by batting average again.

Test all methods in your class(es) manually in your driver or with JUnit

Made in Java Programming Language!

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

//Baseball_Position.java

public enum Baseball_Position {

             Pitcher,

             Catcher,

             FirstBaseman,

             SecondBaseman,

             ThirdBaseman,

             Shortstop,

             LeftFielder,

             CenterFielder,

             RightFielder;

}

//end of Baseball_Position.java

//BaseballPlayer.java

public class BaseballPlayer {

      

       private String name;

       private Baseball_Position position;

       private int hits;

       private int atBats;

       private double batting_average;

       public BaseballPlayer()

       {

             name="";

             position=Baseball_Position.Catcher;

             hits=0;

             atBats=0;

             batting_average = 0;

       }

      

       public BaseballPlayer(String name, Baseball_Position position, int hits, int atBats)

       {

             this.name = name;

             this.position = position;

             setHits(hits);

             setAtBats(atBats);

             setBattingAverage();

       }

      

       private void setBattingAverage()

       {

             if(atBats > 0)

                    batting_average = ((double)Math.round((((double)hits)/atBats)*1000))/1000;

             else

                    batting_average = 0;

       }

      

       public void setHits(int hits)

       {

             if(hits >= 0)

                    this.hits = hits;

             else

                    this.hits = 0;

                   

       }

      

       public void setAtBats(int atBats)

       {

             if(atBats >=0)

                    this.atBats = atBats;

             else

                    this.atBats = 0;

       }

      

       public void setName(String name)

       {

             this.name = name;

       }

      

       public void setPosition(Baseball_Position position)

       {

             this.position = position;

       }

      

       public String getName()

       {

             return name;

       }

      

       public Baseball_Position getPosition()

       {

             return position;

       }

      

       public int getHits()

       {

             return hits;

       }

      

       public int getAtBats()

       {

             return atBats;

       }

      

       public double getBattingAverage()

       {

             return batting_average;

       }

      

       public boolean equals(BaseballPlayer other)

       {

             if((name.equalsIgnoreCase(other.getName())) && (position.equals(other.getPosition())) && (hits == other.getHits()) && (atBats == other.getAtBats()))

                    return true;

             return false;

       }

      

       public String toString()

       {

             return("Name : "+name+" Position : "+position+" Hits : "+hits+" atBats : "+atBats+" Batting Average : "+String.format("%.3f", batting_average));

       }

      

}

//end of BaseballPlayer.java

//MainBaseballPlayer.java : Driver program to test the BaseballPlayer

public class MainBaseballPlayer {

             

       // method to sort the players by batting average in descending order

       public static void sort(BaseballPlayer players[])

       {

             int max;

             for(int i=0;i<players.length-1;i++)

             {

                    max = i;

                    for(int j=i+1;j<players.length;j++)

                           if(players[j].getBattingAverage() > players[max].getBattingAverage())

                                 max= j;

                    if(max != i)

                    {

                           BaseballPlayer temp = players[i];

                           players[i] = players[max];

                           players[max] = temp;

                    }

             }

       }

      

       public static void main(String[] args) {

            

             BaseballPlayer players[] = new BaseballPlayer[9];

             players[0] = new BaseballPlayer("James Cordon",Baseball_Position.Shortstop,12,50);

             players[1] = new BaseballPlayer("Shaun Marsh",Baseball_Position.Pitcher,9,30);

             players[2] = new BaseballPlayer("Paul Day",Baseball_Position.Catcher,34,60);

             players[3] = new BaseballPlayer("Henry Fig",Baseball_Position.FirstBaseman,45,100);

             players[4] = new BaseballPlayer("Michael Hogg",Baseball_Position.SecondBaseman,34,80);

             players[5] = new BaseballPlayer("John Smith",Baseball_Position.LeftFielder,25,70);

             players[6] = new BaseballPlayer("Jack Swann",Baseball_Position.CenterFielder,44,150);

             players[7] = new BaseballPlayer("Jaden Shimp",Baseball_Position.ThirdBaseman,56,120);

             players[8] = new BaseballPlayer("Henry Fox",Baseball_Position.RightFielder,35,100);

            

             int totalHits = 0;

            

             System.out.println("Baseball Players : ");

            

             for(int i=0;i<players.length;i++)

             {

                    System.out.printf("\nBatting average of %s : %.3f",players[i].getName(),players[i].getBattingAverage());

                    totalHits += players[i].getHits();

             }

            

             System.out.println("\n\nTotal number of hits : "+totalHits);

             System.out.println("\nBaseball Players with batting average >= 0.300");

             for(int i=0;i<players.length;i++)

                    if(players[i].getBattingAverage() >= 0.300)

                           System.out.println(players[i].getName());

             System.out.println("\nSorted list of players : ");

             sort(players);

             for(int i=0;i<players.length;i++)

             {

                    System.out.println(players[i]);

             }

            

       }

}

//end of MainBaseballPlayer.java

Output:

Add a comment
Know the answer?
Add Answer to:
Write a class that encapsulates the concept of a baseball player with the important attributes (name,...
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
  • write a C# program using replit that uses a loop to input # at bats and # of hits for each of the 9 baseball players on...

    write a C# program using replit that uses a loop to input # at bats and # of hits for each of the 9 baseball players on a team. Team name, player name, and player position will also be input.(two dimensional array) The program should then calculate and print the individual batting average and, after all 9 players have been entered, calculate and print the team batting average. Example of inputs and Outputs... Enter the Team name: (one time entry)...

  • Homework 18: Problem 2 Previous Problem List Next (1 point) A baseball player has a lifetime...

    Homework 18: Problem 2 Previous Problem List Next (1 point) A baseball player has a lifetime batting average of 0.288. If, in a season, this player has 390 "at bats', what is the probability he gets 115 or more hits? Probability of 115 or more hits Preview My Answers Submit Answers You have attempted this problem 6 times. Your overall recorded score is 0%. You have unlimited attempts remaining. Email Instructor

  • IN JAVA Write a class Store which includes the attributes: store name, city. Write another class...

    IN JAVA Write a class Store which includes the attributes: store name, city. Write another class encapsulating an Art Gallery, which inherits from Store. An Art Gallery has the following additional attributes: how many paintings are sold every year and the number of artists submitting artwork. Code the constructor, accessors, mutators, toString and equals method of the super class Store. Code the constructor, accessors and mutators for the subclass Art Gallery. In the Art Gallery class, also code a method...

  • Create a struct for a baseball player. Include the player's Name (string), Batting Average (percentage), Home...

    Create a struct for a baseball player. Include the player's Name (string), Batting Average (percentage), Home Runs (int), RBI's (int), Runs Scored (int), Stolen bases (int), current salary (float) and current team (string). Create three players using your struct and then display the stats from each player to the screen using the members of the struct- three extra credit points for doing this for all members of the struct in a function.

  • Help me figure this problem out, please. Use a list to store the players Update the...

    Help me figure this problem out, please. Use a list to store the players Update the program so that it allows you to store the players for the starting lineup. This should include the player’s name, position, at bats, and hits. In addition, the program should calculate the player’s batting average from at bats and hits. Console ================================================================ Baseball Team Manager MENU OPTIONS 1 – Display lineup 2 – Add player 3 – Remove player 4 – Move player 5...

  • Write a class Store which includes the attributes: store name, city. Write another class encapsulating an...

    Write a class Store which includes the attributes: store name, city. Write another class encapsulating an Art Gallery, which inherits from Store. An Art Gallery has the following additional attributes: how many paintings are sold every year and the number of artists submitting artwork. Code the constructor, accessors, mutators, toString and equals method of the super class Store. Code the constructor, accessors and mutators for the subclass Art Gallery. In the Art Gallery class, also code a method returning the...

  • Chapter 8 Python Case study Baseball Team Manager For this case study, you’ll use the programming...

    Chapter 8 Python Case study Baseball Team Manager For this case study, you’ll use the programming skills that you learn in Murach’s Python Programming to develop a program that helps a person manage a baseball team. This program stores the data for each player on the team, and it also lets the manager set a starting lineup for each game. After you read chapter 2, you can develop a simple program that calculates the batting average for a player. Then,...

  • c++ A menu-driven program gives the user the option to find statistics about different baseball players....

    c++ A menu-driven program gives the user the option to find statistics about different baseball players. The program reads from a file and stores the data for ten baseball players, including player’s team, name of player, number of homeruns, batting average, and runs batted in. (You can make up your data, or get it online, for example: http://espn.go.com/mlb/statistics ) Write a program that declares a struct to store the data for a player. Declare an array of 10 components to...

  • Anyone helps me in a Java Languageif it it is possible thanks. Write a class called...

    Anyone helps me in a Java Languageif it it is possible thanks. Write a class called Player that holds the following information: Team Name (e.g., Ravens) . Player Name (e.g., Flacco) . Position's Name (e.g. Wide reciver) . Playing hours per week (e.g. 30 hours per week). Payment Rate (e.g., 46 per hour) . Number of Players in the Team (e.g. 80 players) . This information represents the class member variables. Declare all variables of Payer class as private except...

  • Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int....

    Read through the code of the class Player, noting it has two instance variables, name and rank, which are of type String and three further instance variables won, drew and lost which are of type int. There is also an attribute of the class, points, which does not have a corresponding instance variable. Also note the constructor and methods of the class and what they do. TournamentAdmin class code: public class RankAdmin {    /**     * Constructor for objects of class...

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
ADVERTISEMENT