我的情况是我必须为一个类创建一个toString()方法,该方法基本上只从另一个类中获取一堆对象并将所有对象放入一个arraylist中。生成arraylist的类需要这个toString()方法来返回格式化字符串中的所有arraylist对象,该字符串将准备好在控制台中显示。创建放入arraylists的对象的类有一个自己的toString()方法,它返回一个格式很好的所有数据的字符串,也许我可以为另一个类的toString中的每个对象调用这个toString()方法( ) 方法?这是代码:
创建基础对象的类:
public class Batter {
private String firstName;
private String lastName;
private int atBats;
private int hits;
private int doubles;
private int triples;
private int homeRuns;
public Batter(String fName, String lName){
firstName = fName;
lastName = lName;
}
public void setBats(int batCount){
atBats = batCount;
}
public void setHits(int hitCount){
hits = hitCount;
}
public void setDoubles(int doubleCount){
doubles = doubleCount;
}
public void setTriples(int tripleCount){
triples = tripleCount;
}
public void setHR(int homeRunCount){
homeRuns = homeRunCount;
}
public double getAve(int hits, int bats){
double average = hits / bats;
return average;
}
public String getName(){
String fullName = this.lastName + "," + this.firstName;
return fullName;
}
public boolean equals(){
return true;
}
public String toString(){
return "Player: "+getName()+"\nAt Bats: "+this.atBats+"\nHits: "+this.hits+"\nDoubles: "+this.doubles+"\nTriples: "+this.triples+"\nHome Runs: "+this.homeRuns;
}
}
将上述类生成的对象放入arraylist的类 - 这是我不知道该怎么做的地方。我需要编写的代码将在此类的toString()方法中。同样,它的目标是以格式很好的字符串返回所有对象的数据,也许以某种方式使用在另一个类中创建的那些对象的toString()方法:
public class BatterDB
{
private ArrayList<Batter> theBatters = new ArrayList<Batter>(); // ArrayList of Batters
private int num; // int to store logical size of DB
// Initialize this BatterDB
public BatterDB()
{
num = 0;
}
public void addBatter(Batter b)
{
theBatters.add(b);
num++;
}
public Batter removeBatter(Batter b)
{
return theBatters.remove(0);
}
// Return logical size of the DB
public int numBatters()
{
return theBatters.size();
}
public Batter findBatter(String fName, String lName)
{
return theBatters.get(0); //change
}
public void sortName()
{
}
public void sortAve()
{
}
public String toString()
{
//Where I'm lost
}
public String toStringFile()
{
return "toStringFile()";
}
}
答案 0 :(得分:0)
您要做的是将List theBatters
变成String
。在toString
的{{1}}方法中,执行以下操作:
BatterDB