Creating Classes Help public class Player { private String name; private int hit
ID: 653620 • Letter: C
Question
Creating Classes Help
public class Player
{
private String name;
private int hits;
private int atBats;
private float batAvg;
//create a constructor that will receive the name of the player and init all other class data to 0
//create a method that will receive hits and at bats for a player and add them to his total
//create a method that will calculate a players batting average using the current instance data
//create a toString method that will format the instance data on 1 line. The average should be displayed to 3 decimal places. The name should be exactly 15 characters long.
}
Explanation / Answer
package newlol;
public class Player {
private String name;
private int hits;
private int atBats;
private float batAvg;
public Player(String name) throws Exception {
super();
if (name.length() != 15) {
throw new Exception("Length of the name should be characters");
}
this.name = name;
this.hits = 0;
this.atBats = 0;
this.batAvg = 0;
}
public void addToTotal(int hits, int atBats) {
this.hits = this.hits + hits;
this.atBats = this.atBats + atBats;
}
public void updateAverage() {
this.batAvg = (this.hits) / (this.atBats);
}
@Override
public String toString() {
return "Player [name=" + name + ", hits=" + hits + ", atBats=" + atBats
+ ", batAvg=" + batAvg + "]";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.