84.6k views
22 votes
The BaseballPlayer class stores the number of hits and the number of at-bats a player has. You will complete this class by writing the constructor. Write a method called: public BaseballPlayer The constructor should take three parameters to match the three instance variables in the class and then initialize the instance variables with these parameters. The parameters should be ordered so that the name of the baseball player is input first, then their hits, and at bats. In the BaseballTester class, print a call to printBattingAverage to test your constructor. 5.2.5: Batting Average 1 public class Baseballtester 2-{ 3 4- 5 6 7 8 public static void main(String[] args) { BaseballPlayer babeRuth = new BaseballPlayer("Babe Ruth", 2873, 8399); System.out.println(babeRuth); // Call the function printBattingAverage here } 9 10 11 12 0 5.2.5: Batting Average 1 public class Baseballplayer 2-{ private int hits; private int atBats; 5 private String name; // Add constructor here public void printBattingAverage { double battingAverage hits / (double) atBats; System.out.println(battingAverage); } 6 7 8 9 10 - 11 12 13 14 15 16 - 17 18 19 20 21 public String toString() { return name + ": + hits + "/" + atBats; } }

User Nick Kitto
by
5.6k points

1 Answer

12 votes

Answer:

class BaseballPlayer {

private int hits;

private int atBats;

private String name;

public BaseballPlayer(String n,int h,int a) {

name=n;

hits=h;

atBats=a;

}

public void printBattingAverage() {

double battingAverage = hits / (double)atBats;

System.out.println(battingAverage);

}

public String toString() {

return name + ": "+hits+"/"+atBats;

}

}

public class Baseballtester{

public static void main(String[] args){

BaseballPlayer babeRuth = new BaseballPlayer("Babe Ruth", 2873, 8399);

System.out.println(babeRuth);

babeRuth.printBattlingAverage();

}

}

Step-by-step explanation:

The BaseballPlayer class is used to get and hold data of an instance of a baseball player. the instance object holds the name, number of hits and bats of the player.

The constructor is used to initialize the name, hits and atBats variables of an instance. The "printBattlingAverage" method returns the ratio of the hits and atBat variable while the string method "toString" returns the name and the hits to atBats ratio in string format.

User Dereckson
by
5.3k points