Creating Classes Help public class Player { private String name; private int hit
ID: 652535 • 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
#include<iostream>
#include<string>
#include<sstream>
using namespace std;
class Player
{
private :
string name ;
int hits;
int atBats;
float batAvg;
int total;
public:
//create a constructor that will receive the name of the player and init all other class data to 0
Player(string str)
{
name=str;
hits=0;
atBats=0;
batAvg=0;
}
//create a method that will receive hits and at bats for a player and add them to his total
int total_hits(int hts,int atBts)
{
hits=hts;
atBats=atBts;
batAvg= hits + atBats;
return ( batAvg);
}
//create a method that will calculate a players batting average using the current instance data
float average()
{
return ( batAvg/=2 );
}
//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.
string toString(string str)
{
int pos;
string Token;
//name=str.substr(0,15);
//cout<<"Name = "<<name<<endl;
ostringstream ss;
istringstream StrStream(str);
int i=0;
while (StrStream)
{
getline(StrStream, Token, ' ');
cout << Token << endl;
switch(i)
{
case 0:
name=Token;
break;
case 1:
hits=atoi(Token.c_str());
break;
case 2:
atBats=atoi(Token.c_str());
break;
}
i++;
}
batAvg= float ( hits + atBats)/2;
ss << batAvg;
return ss.str();
}
};
int main()
{
Player one("John");
one.total_hits(17,20);
float avg;
avg= one.average();
cout.setf(ios::fixed,ios::floatfield);
cout.precision(3);
cout<<"Average= "<<one.toString("Jacobabhgabahabs 121 20");
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.