This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 7 years ago.
Recently, I've learned something: I have no idea how to use toString methods.(If you've seen my last question, you'll get a prime example.)
Anyways, I was going through some unfinished programs of mine from an Intro to Java class I took last year and this one I just cannot finish. My effort to become a better programmer has faced the ultimate challenge: toString methods.
The basic overview is that I had to write a 'Grocery' store program where the ShoppingCart class was an ArrayList of Grocery Objects.
There's just one problem- when I run the program I get
Grocery.ShoppingCart#2eeb3c84
My old enemy, the toString() looks like it is required.
The output I should be getting is this:
[Tomatoes: 2.76 $1.39, Mac & Cheese: 6.0, $0.89]
now if I print out the Cart ArrayList (System.out.println(Cart)) I get this:
[Tomatoes, 2.76, $1.39, Mac & Cheese, 6.0, $0.89]
Exactly the output I should be getting.
How does this happen? How can I fix this?
When I print out the Cart Arraylist, I get the output I want (I still get the "Grocery.ShoppingCart#). I have to find some way to replace the "Grocery.ShoppingCart#[etc.]" with the ArrayList.
Anybody have any ideas?
Thanks!
-Chris
Bits of the ShoppingCart class:
ArrayList<Grocery> Cart = new ArrayList<Grocery>();
int size = Cart.size();
double tot = 0.0;
public ShoppingCart(){
}
...
public void printReceipt() {
Grocery temp = new Grocery();
double pr = 0.0;
double qu = 0.0;
String n = "";
String con = "IF YOU SEE ME SOMETHING IS WRONG!";
double gr = 0.0;
for(int k = 0; k < size; k++){
temp = Cart.get(k);
n = temp.getName();
qu = temp.getQuan();
pr = temp.getPrice();
tot = qu * pr;
con = n + ":" + " " + qu + ", " + pr + "\t\t Total: $" + tot;
}
System.out.println("====RECIEPT====");
System.out.println("Grand Total:\t" + "$" + totalPr());
}
Grocery Class Printing out ShoppingCart
public static void testShoppingCartClass ()
{
System.out.println ("Testing ShoppingCart class\n");
ShoppingCart myCart = new ShoppingCart();
System.out.println (" ShoppingCart using default constructor: ");
System.out.println ("\t" + myCart);
myCart.addItem (new Grocery("Tomatoes", 2.76, 1.39));
myCart.addItem (new Grocery("Mozzarella", 0.95, 4.59));
myCart.addItem (new Grocery("Mac & Cheese", 6, 0.89));
System.out.println ("\n ShoppingCart after adding three items: ");
System.out.println ("\t" + myCart);
myCart.removeItem (1);
System.out.println ("\n ShoppingCart after removing an item: ");
System.out.println ("\t" + myCart);
System.out.println ("\n\nPrinting receipt: \n");
myCart.printReceipt();
System.out.println ("\n\nDone testing ShoppingCart class\n\n");
}
You can override toString to return whatever you want. In your case, it looks like you want to do:
class ShoppingCart {
ArrayList<Grocery> cart;
...
#Override
public String toString() {
return cart.toString();
}
}
Java's default toString() method on any object will print out what you're seeing ("Grocery.ShoppingCart#[etc.]"). This is the Class with the object's hash code appended to the end of it.
From what I see in that output, you're calling .toString() on an instance of the ShoppingCart class which is why you're getting that output.
In order for that class to print out the contents of the ArrayList - Cart, which is a member of that class, you will need to override the toString() method of that class to print the contents of the ArrayList. Once it is overridden, your implementation of the toString() will be called rather than the default.
public String toString() {
// return the string that you want.
}
toString() is called on shoppingCart when you call System.out.println(shoppingCart) in order to retrieve the string to print.
Yes, you'll need a toString() on your ShoppingCart.
If I understand what you're trying to do though, may I suggest going with a more conventional Java bean approach? Here's a simplistic view.
Bean with getter and setters. A better name for this might be Item. You can change the types as needed as well.
public class Grocery {
public BigDecimal getQuantity() {
return quantity;
}
public void setQuantity(BigDecimal quantity) {
this.quantity = quantity;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private BigDecimal quantity;
private BigDecimal price;
private String name;
#Override
public String toString() {
return "Grocery{" +
"quantity=" + quantity +
", price=" + price +
", name='" + name + '\'' +
'}';
}
}
And your cart:
public class ShoppingCart {
List<Grocery> contents;
public void initialize() {
contents = new ArrayList<Grocery>();
}
public void addItem(Grocery item) {
contents.add(item);
}
public void removeItem(Grocery item) {
boolean wasRemoved = contents.remove(item);
if (!wasRemoved) {
System.out.println("Item not found in cart: " + item);
}
}
public List<Grocery> getContents() {
return contents;
}
#Override
public String toString() {
return "ShoppingCart{" +
"contents=" + contents +
'}';
}
}
And some class to run it:
public class CartRun {
public static void main(String[] args) {
ShoppingCart cart = new ShoppingCart();
cart.initialize();
Grocery item = new Grocery();
item.setName("Tomatoes");
item.setPrice(BigDecimal.valueOf(2));
item.setQuantity(BigDecimal.valueOf(3));
cart.addItem(item);
System.out.println("Item="+item);
System.out.println("Cart="+cart);
}
}
Output:
Item=Grocery{quantity=3, price=2, name='Tomatoes'}
Cart=ShoppingCart{contents=[Grocery{quantity=3, price=2, name='Tomatoes'}]}
Also, stay away from capital letters (e.g., "Cart") for variable names because it looks like a static method call by convention.
Related
So, I'm working on a coding assignment and I've reached an impasse. Here is the feedback I received from my professor and afterwards, I'll attach the code I've been working on and further explain the issue:
Thank you for reaching out. It looks good! The only thing I would suggest is adding high level comments throughout your code and testing the set() methods on the Team objects in your MainTeamClass.java program to ensure that the set() mutator methods work as intended. Call the set() method with a test value and then call the get() method to see if it is the same value.
Here is a copy of the code:
public class Team
{
private String team;
private int points;
private double average;
public Team()
{
team = " Default";
}
public Team(String startTeam, int startPoints, double startAverage)
{
team = startTeam;
points = startPoints;
average = startAverage;
}
public String getTeam()
{
return team;
}
public int getPoints()
{
return points;
}
public double getAverage()
{
return average;
}
public void setTeam(String newTeam)
{
team = newTeam;
}
public void setPoints(int newPoints)
{
if (newPoints >= 0)
{
points = newPoints;
}
}
public void setAverage(double newAverage)
{
if (newAverage >= 0.0)
{
average = newAverage;
}
}
}
And the Main class:
public class MainTeamClass { public static void main(String[] args)
{
Team sanfran = new Team();
String sanfranTeam = sanfran.getTeam();
int sanfranPoints = sanfran.getPoints();
double sanfranAverage = sanfran.getAverage();
System.out.println(" The team name is:" + sanfran.getTeam()
+ "\n The number of points earned equals " + sanfran.getPoints()
+ "\n The average season score is:" + sanfran.getAverage());
Team cowboys = new Team("Dallas Cowboys", 36, 43.5);
String cowboysTeam = cowboys.getTeam();
int cowboysPoints = cowboys.getPoints();
double cowboysAverage = cowboys.getAverage();
System.out.println("\n The team name is: " + cowboys.getTeam()
+ "\n The number of points earned equals " + cowboys.getPoints()
+ "\n The average season score is: " + cowboys.getAverage()); } }
Based on this code, how would I go about testing the set() method and the get() method? Can someone explain how to do so and also provide an example? It wasn't in the chapter for this week in class and I've searched the web for some assistance but to no avail, so I would appreciate as much feedback as possible. Thank you in advance!
"Call the set() method with a test value and then call the get() method to see if it is the same value.": means that the the value passed to the set method is the same value that has to be returned from the get method, something like this:
Team team = new Team ();
String test = "stringForTest";
team.setTeam(test);
if(!team.getTeam().equals(test)) {
System.out.println("Problem with set/get method!");
}
You can different methods, one of them assertion and run using java -ea <program_name>
enable assertion
public class MainTeamClass {
public static void main(String[] args) {
Team cowboys = new Team();
cowboys.setTeam("Dallas Cowboys");
String cowboysTeam = cowboys.getTeam();
assert cowboysTeam == "Dallas Cowboys" : "cowboysTeam Not valid";
cowboys.setPoints(36);
int cowboysPoints = cowboys.getPoints();
assert cowboysPoints == 36 : "cowboysPoints Not valid";
cowboys.setAverage(43.5);
double cowboysAverage = cowboys.getAverage();
assert cowboysAverage == 43.5 : "cowboysAverage Not valid";
}
}
I'm making a solar system model that uses takes different solar systems and sets of planets through the use of classes. I've chosen to use an arraylist to store each object of a planet within the solar system although am now struggling to output the data in a suitable format.
The format i am looking for in the toString() method is 'Planet X has a mass of A Earths, is BAU from its star, and orbits in C years: could be habitable? D'
I have attempted using for loops to print each planet however don't believe this is the correct way as a return will cause the loop to stop. Many thanks
SolarSystem.java
import java.util.ArrayList;
public class SolarSystem {
private String systemName;
private double systemLuminosity;
public SolarSystem(String name, double luminosity) {
this.systemName = name;
this.systemLuminosity = luminosity;
}
ArrayList<Planet> list = new ArrayList<>();
public void addPlanet(String name, double mass, double distance) {
list.add(new Planet(name, mass, distance, systemLuminosity));
}
public void planetProperties() {
}
public String toString() {
System.out.println(list.size());
String results = "+";
for (Planet planet : list) {
results += planet.getName(); //if you implement toString() for Dog then it will be added here
}
return results;
}
}
Planet.java
public class Planet {
private String planetName;
private double planetMass;
private double distanceFromStar;
private double orbitalPeriod;
private String isHabitable;
public Planet(String name, double mass, double distance, double systemLuminosity) {
setName(name);
setMass(mass);
setDistanceFromSun(distance);
setOrbitalPeriod(distance);
setIsHabitable(mass, distance, systemLuminosity);
}
public void setName(String name) {
planetName = name;
}
public String getName() {
return planetName;
}
public void setMass(double mass) {
planetMass = mass;
}
public double getMass() {
return planetMass;
}
public void setDistanceFromSun(double distance) {
distanceFromStar = distance;
}
public double getDistanceFromStar() {
return distanceFromStar;
}
public void setOrbitalPeriod(double distance) {
orbitalPeriod = Math.sqrt(distance*distance*distance);
}
public double getOrbitalPeriod() {
return orbitalPeriod;
}
public void setIsHabitable(double mass, double distance, double luminosity) {
if (mass >= 0.6 && mass <= 7.0) {
if ((distance >= 0.75 * Math.sqrt(luminosity)) && (distance <= 2.0 * Math.sqrt(luminosity))) {
isHabitable = "yes";
} else {
isHabitable = "no";
}
} else {
isHabitable = "no";
}
}
public String getIsHabitable() {
return isHabitable;
}
}
Main.java
public class Main {
public static void main(String[] args) {
//Create our solar system
SolarSystem ourSystem = new SolarSystem("Our System",1.0);
//Add planets in our solar system
ourSystem.addPlanet("Mercury", 0.055, 0.387);
ourSystem.addPlanet("Venus", 0.815, 0.723);
ourSystem.addPlanet("Earth", 1.0, 1.0);
ourSystem.addPlanet("Mars", 0.107, 1.52);
ourSystem.addPlanet("Jupiter", 317.8, 5.20);
ourSystem.addPlanet("Saturn", 95.2, 9.58);
ourSystem.addPlanet("Uranus", 14.5, 19.20);
ourSystem.addPlanet("Neptune", 17.1, 30.05);
System.out.println(ourSystem.toString());
}
}
You need to implement a toString() method inside your Planet class, for example:
class Planet {
private String planetName;
private double planetMass;
private double distanceFromStar;
private double orbitalPeriod;
private String isHabitable;
#Override
public String toString() {
return String.format(
"Planet %s has a mass of %f Earths, is %f from its star, and orbits in %f years: could be habitable? %s%n",
this.planetName, this.planetMass, this.distanceFromStar, this.orbitalPeriod, this.isHabitable);
}
}
Then inside your SolarSystem class you can create a list with something like this, you already have that part almost correct but I've changed getName to toString:
#Override
public String toString() {
StringBuilder buf = new StringBuilder();
for (Planet planet : list) {
buf.append(planet);
}
return buf.toString();
}
If you want to print out a description for the entire solar system (the entire array list of planets), I would suggest to implement the toString() method inside the Planet class. Doing so will allow you to simply iterate over the Planets array list, and just call planet.toString(). Encapsulating the logic for a singular planet inside the Planet class is the way to go.
You have to redefine toString in the Planet class and replace the toString of SolarSystem to use it.
public class Planet {
...
public String toString() {
return "Planet " + planetName + " has a mass of " + planetMass +
" Earths, is BAU from its star, and orbits in " + orbitalPeriod +
" years: could be habitable? " + isHabitable;
}
}
public class SolarSystem {
...
public String toString() {
String results = "";
for (Planet planet : list) {
results += planet.toString() + "\n"; // Use the toString of planet and add a new line
}
return results;
}
}
Note: for performance reasons as commented by oleg it is preferable to use a StringBuilder to concatenate strings. In this situation where you have few items and the problem is not related to the performances you can leave the + operator.
Growing your java knowledge you will find useful functions like String.join:
Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
That will help you mantaining your code simpler and cleaner replacing this:
public String toString() {
String results = "";
for (Planet planet : list) {
results += planet.toString() + "\n"; // Use the toString of planet and add a new line
}
return results;
}
with
public String toString() {
return String.join("\n", list);
}
but my tip is to start from the basis of java before trying to use more advanced functions. Otherwise you will use them without knowing what happens behind the scenes
To echo other posters, you need to define a custom toString() method in the planet class first. Please see my suggestions below. They are presented as pseudo-code typed on the fly, not actual code (for there might be a few things here and there that might not compile.)
But the pseudo-code should give an idea for a possible solution. Hit me up if you still have questions.
Based on your requirements:
The format i am looking for in the toString() method is 'Planet X has
a mass of A Earths, is BAU from its star, and orbits in C years: could
be habitable? D'
Your Planet.toString method could look as follows (this is pseudo-code, not bound to be compilable, but you get the gist of it.)
public class Planet {
/* your class as it is, with the
* addition of a possible toString
* implementation */
public String toString(){
return String.format(
"Planet: %s, " +
"mass: %f, " +
"distance: %f, " +
"orbital period: %f, " +
"habitable: %b"
this.getName(),
this.getMass(),
this.getDistanceFromStar(),
this.getOrbitalPeriod(),
this.getIsHabitable());
}
}
Then, your SolarSystem class should have an appropriate toString method that loops over the collection of planets in it. Your original toString method had the right idea, I'm just extending the notion.
public class SolarSystem {
/*
Your solar system class plus some changes
...
*/
public String getName(){
return this.systemName;
}
public String getLuminosity(){
return this.systemLuminosity;
}
public int getPlanetCount(){
return this.list.size();
}
public String toString() {
final StringBuffer buffer = new StringBuffer();
buffer.append(
String.format("System: %s\nLuminosity: %f\nPlanet Count:%d\n",
this.getName(),
this.getLuminosity(),
this.getPlanetCount()
)
);
for (final Planet planet : list) {
buffer.append('\t')
.append(planet.getString())
.append('\n');
}
return buffer.toString();
}
}
Now, I'm a bit confused with this:
I have attempted using for loops to print each planet however don't
believe this is the correct way as a return will cause the loop to
stop. Many thanks
A return statement will stop a loop if the return is done within the loop.
A return statement done within a function called within the loop will not end the loop.
That is, a return only ends the function that makes the return call, not functions up in the call chain.
Compare this
for(Foo f : fooList){
if(something){
return; // this will stop the loop
}
}
With this
for(Foo f : fooList){
if(something){
callThisFu(); // the return within callThisFu *will not* exit the loop
}
}
Hope this clear this up.
This question already has answers here:
how to print the index number of elements in the ArrayList using for each looping
(4 answers)
Closed 4 years ago.
This is my code
ArrayList<Restaurant> restaurant= new ArrayList<Restaurant>();
Inside Restaurant class,
#Override
public String toString() {
int i=1;
return "\n"+(i++)+". "+this.restaurantName +
"\t\t"+this.location;
}
I want to print like this
[ 1. pizzahut bangalore, 2. dominos delhi]
instead it prints
[ 1. pizzahut bangalore, 1. dominos delhi]
Help in code needed.
Here is another solution, I am not sure what actual problem you have, so just provide another possible solution. this might work for you.
public class Restaurant {
static int index = 1;
String restaurantName;
String location;
int curIndex;
Restaurant(final String restaurantName, final String location) {
this.restaurantName = restaurantName;
this.location = location;
this.curIndex = index++;
}
public static void main(final String[] input) {
final ArrayList<Restaurant> restaurant = new ArrayList<Restaurant>();
restaurant.add(new Restaurant("pizzahut", "bangalore"));
restaurant.add(new Restaurant("dominos", "delhi"));
restaurant.forEach(r -> System.out.println(r));
}
public String toString() {
return "\n" + curIndex + ". " + this.restaurantName +
"\t\t" + this.location;
}
}
ArrayList<Restaurant> restaurantList= new ArrayList<Restaurant>();
// your login to insert the elements in the array list
// iterate list
int index=1;
for(Restaurant r : restaurantList){
System.out.println(String.valueOf(index++)+": "+ r);
}
Inside Restaurant class,
#Override
public String toString() {
return this.restaurantName + "\t\t"+this.location;
}
I am trying to display all of the elements in the ArrayList plantList.
My main program will add, delete, search, filter, and display all of the plants of four different child classes. Everything "seems" to be working except when I display.
~I will only including portions of my code that are relevant to the questions.
A little background: I am a student and this is my first time working with inheritance/polymorphism.
1)How do I distinguish between the different objects since they all have different parameters, at the time of displaying?
2) Any suggestions on how to improve the performance/logic of what I'm doing? A little explanation would be great.
//Parent class
public class Plant{
private String name;
private String id;
private String color;
public Plant(String name, String id, String color){
this.name = name;
this.id = id;
this.color = color;
}
public String getName(){
return this.name;
}
public void setName(String name){
name = this.name;
}
public String getId(){
return this.id;
}
public void setId(String id){
id = this.id;
}
public String getColor(){
return this.color;
}
public void setColor(String color){
color = this.color;
}
}
//one of several child classes
public class Flower extends Plant{
private boolean thorns;
private boolean smell;
public Flower(String name, String id, String color, boolean blnThorns, boolean blnSmell){
super(name, id, color);
thorns = blnThorns;
smell = blnSmell;
}
public boolean isThorns(){
return thorns;
}
public void setThorns(boolean blnThorns){
thorns = blnThorns;
}
public boolean isSmell(){
return smell;
}
public void setSmell(boolean blnSmell){
smell = blnSmell;
}
}
// portion of the main driver
ArrayList<Plant> plantList = new ArrayList<Plant>();
//adding a flower to the plantList
System.out.println("\nEnter the name of the flower to add: ");
name = add.nextLine();
System.out.println("\nEnter the ID code: ");
id = add.nextLine();
System.out.println("\nEnter the color: ");
color = add.nextLine();
System.out.println("\nAre there thorns present? (True/False) ");
blnThorns = add.nextBoolean();
System.out.println("\nDoes the flower smell? (True/False) ");
blnSmell = add.nextBoolean();
plantList.add(new Flower(name, id, color, blnThorns, blnSmell));
System.out.println("Flower inserted.");
System.out.println();
break;
//displaying all plants
for( int i = 0; i < plantList.size(); i++){
System. out.println("\t" + (i+1) + ":");
System.out.print("\n\tName: " + plantList.get(i).getName());
System.out.print("\n\tName: " + plantList.get(i).getId());
System.out.print("\n\tColor: " + plantList.get(i).getColor());
if(plantList instanceof Flower){ // HERE I am not sure what I'm doing or how to do it
System.out.print("\n\tThorns presence: " + plantList.get(i).isThorns()); /* this is an example of what is not working properly */
System.out.print("\n\tSmell presence: " + plantList.get(i).isSmell()); /* this is an example of what is not working properly*/
System.out.println("\n");
}
}
If by "display" you mean "print some sort of string to the console or other output", then the answer is fairly simple: there's no need to use instanceof at all. All you need to do is override the toString method in each different class that you want to be displayable, then when you want to display an object (even if you don't know exactly what type it is), just call toString on it and print the result. Polymorphism will do the job of picking which toString method implementation to call.
Here's how it would look in your specific example.
In the Plant class:
#Override
public String toString() {
return "\n\tName: " + getName()
+ "\n\tName: " + getId()
+ "\n\tColor: " + getColor();
}
Then, in the Flower class:
#Override
public String toString() {
return super.toString()
+ "\n\tThorns presence: " + isThorns()
+ "\n\tSmell presence: " + isSmell();
}
Finally, to display all plants:
for (Plant plant : plantList) {
System.out.println(plant);
}
Note that toString is called automatically when you pass any Object to System.out.println.
You were really close. You just needed to check against the element of the list, not the list itself, when you did the instanceof check. Then, if it is in fact an instance of Flower, then you need to cast the list element to a Flower and make the method calls from there.
Like this:
for(int i = 0; i < plantList.size(); i++){
System.out.println("\t" + (i+1) + ":");
System.out.print("\n\tName: " + plantList.get(i).getName());
System.out.print("\n\tName: " + plantList.get(i).getId());
System.out.print("\n\tColor: " + plantList.get(i).getColor());
if (plantList.get(i) instanceof Flower) {
Flower flower = (Flower)plantList.get(i);
System.out.print("\n\tThorns presence: " + flower.isThorns());
System.out.print("\n\tSmell presence: " + flower.isSmell());
System.out.println("\n");
}
}
Okay, I don't know If I wrote a code correctly please check. So I created software for a store that sells one type of item. And each instance of my class should be an item of merchandise my store sells.
For example if my store sells neckties, I would design a necktie class:
class Necktie { …
My class must have five instance variables, including at least one of type integer, at least one of type String and one called price which must be double. Also it should have a toString method that accepts no parameters and returns a description of the item. It should have a constructor. The constructor can take however many parameters you choose, but it must set all instance variables.
• It should contain an accessor method for each instance variable.
• It should contain no unnecessary instance variables. Any information that does not need to be stored in an instance of your class should be stored as local variables.
Here is the code below. (incomplete, because I am kinda stuck..Please check if I did it correctly. If not, then please correct me.)
public class Pets {
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
String color, pattern;
int age, size;
double price;
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
age = age;
size = size;
price = price;
}
public String toString(){ //I don't get this part..
String description;
description = "red";
return description;
}
public String getColor(){
return color;
}
public String getPattern(){
return pattern;
}
public int age(){
return age;
}
public int size(){
return size;
}
public double price(){
return price;
}
}
Where you've written
age = age;
size = size;
price = price;
This is actually not setting the instance variable. You should carry on writing
this.age = age
// etc...
When you write this it tells Java that you're referring to the instance variable, not the local variable
When the main method is called, Java doesn't create an instance of Pets for you. But the rest of your code works on a Pets object, so you'll need to create one somewhere in your main. Thus, instead of:
public static void main(String[] args) {
System.out.print (Pets.toString()); //toString
}
it will be something like
public static void main(String[] args) {
Pets pet = new Pets(........); // creates an instance; you'll need to supply
// the arguments
System.out.print (pet.toString()); // calls toString on this instance
}
That will get past the "cannot make a static reference" error, but there are other problems as described in other answers.
Your main method tries to call a static method toString(), but your toString() method is not static (as it shouldn't be).
For testing purposes, your main method should look like this:
public static void main(String[] args) {
Pets pet = new Pets("red", "plain", 1, 2, 10.25);
System.out.println(pet.toString());
}
In your constructor:
Pets (String color, String pattern, int age, int size, double price){
this.color = color;
this.pattern = pattern;
this.age = age;
this.size = size;
this.price = price;
}
Your toString() method has a typo in the name. It should probably return a description of the attributes of the instance (not an actual description field). For example:
public String toString() {
StringBuilder description = new StringBuilder("Color: ")
.append(color)
.append(", Pattern: ")
.append(pattern)
.append(", Age: ")
.append(age)
.append(", Size: ")
.append(size)
.append(", Price: ")
.append(price);
return description.toString();
}
Your getters should start with get:
public int getAge(){
return age;
}
public int getSize(){
return size;
}
public double getPrice(){
return price;
}
Edit
At the OPs request:
An alternative toString() method which uses String concatenation (bad) and no special formatting:
public String toString() {
return "Color: " + color + ", Pattern: " + pattern + ", Age: " + age + ", Size: " + size + ", Price: " + price;
}