Discussion 05-Sept-2024
- We didn't have time to go into public/private access modifiers in the class today. However, I have put up public/private access modifiers in this code.
- We are printing the values for the purpose of testing our code. Better ways of testing are assertions and Junit (will be covered later)
public class BaseballPlayer {
private String name;
private int atBats;
private int hits;
private static int noOfPlayers = 0;
public BaseballPlayer(String name, int atBats, int hits) {
this.name = name;
this.atBats = atBats;
this.hits = hits;
noOfPlayers++;
}
public BaseballPlayer(String name) {
this.name = name;
noOfPlayers++;
}
public static int numPlayers() {
return noOfPlayers;
}
public double getBattingAvg() {
if(atBats ==0)return 0;
return ((double)hits) / atBats;
}
public void updateStats(int atBats, int hits) {
this.atBats += atBats;
this.hits += hits;
}
}
public class BaseballPlayerTester {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Hello tester!");
BaseballPlayer p1=new BaseballPlayer("Red Smith");
BaseballPlayer p2=new BaseballPlayer("Ann Fin");
int a = BaseballPlayer.numPlayers();//---> 2
System.out.println(a);
BaseballPlayer p3=new BaseballPlayer("Sam Jone", 10, 3);
int b= BaseballPlayer.numPlayers();// ---->3
System.out.println(b);
double c = p3.getBattingAvg();
System.out.println(c);// ----> 0.300000
double d = p1.getBattingAvg();
System.out.println(d);//----> 0.0
p1.updateStats(3, 1);
double e = p1.getBattingAvg();
System.out.println(e);//---->0.333
p3.updateStats(4, 0);
double f = p3.getBattingAvg();
System.out.println(f);//---->0.2142857
System.out.println("Bye tester!");
}
}