I am trying to access a toString method from another class in order to print the elements of the array.
info += "Purchases:\n";
for(int index = 0; index < purchases.size(); index++){
info += "[" + (index + 1) + "] ";
info += purchases.get(index).toString();
info += "\n";
}
I would like the code to access the toString in the Purchases class to print out
public String toString(){
String info;
DecimalF开发者_开发问答ormat formatter = new DecimalFormat("$#0.00");
info= (date.get(Calendar.MONTH) +1) + "/" + date.get(Calendar.DAY_OF_MONTH) + "/" + date.get(Calendar.YEAR);
info += "\t" + vendor + "\t\t";
info += (formatter.format(amount));
return info;
}
How can I do this?
The way you did it is inefficient but it will work.
What is the problem you are seeing?
If you are getting NullPointerException drop the call to .toString()
as it will do this for you anyway (except withou the NPE)
When you override the toString() method of an object, you dont need to call it in order to work like:
myObject.toString();
also for printing arrays i recomend to use the enhanced for loop, it is easier. Example:
List<MyObject> mo = new ArrayList<MyObject>();
for(MyObject s: listObject){
System.out.print(s);
}
The example above would work perfectly if MyObject class overrides the toString() method Note: just imagine that mo is full of objects.
I think you overrided correctly the toString() method the problem is just in your loop. Give a try to the enhanced for loop:
for(Purchase p: purchases) {
System.out.println(p);
}
That should do the job
精彩评论