Adding an unknown number of objects to an arraylist

i have a school assignment which requires me to add an unknown number of instances of a class "fruit" in to an arraylist "basket" and print out the details of each fruit object, my code adds the fruits to the arraylist but seems to override the previous entry each time leaving me with an arraylist of the same project. This is my code so far:

import java.util.*;
public class Question1
{
   public static void main(String[]Augs)
   {
      List<Fruit> basket = new ArrayList<Fruit>();
      int input;
      Scanner inp = new Scanner(System.in);
      String name;
      String colour;
      double mass;
      int k = -1;
      while (true)
      {
         System.out.println("Enter option: (1) add fruit (2) quit:");
         input = inp.nextInt();
         if (input==2)
            break;
         else
         {
             k++;
            System.out.println("Enter name, colour and mass in kg separated by space");
            name = inp.next();
            colour = inp.next();
            mass = inp.nextDouble();
            Fruit temp = new Fruit(name, colour, mass);
            basket.add(temp);
         }
      }
      for (int i = 0; i<basket.size(); i++)
      {
         System.out.println(basket.get(i));
      }
   }
}

//fruit class
public class Fruit
{
   private String name;
   private String colour;
   private double mass;
   public Fruit(String name, String colour, double mass)
   {
      this.name=name;
      this.colour=colour;
      this.mass=mass;
   }
   public String toString()
   {
      return name + " " + colour + " " + mass;
   }
}

Upvotes: 0

Views: 1948

Answers (1)

Ameen
Ameen

Reputation: 2586

Your code looks just fine in terms of adding the fruits to the basket. I think what's getting you is System.out.println(basket.get(i)). You are essentially asking a Fruit object to be printed, but the run time does not know how to do that and as such tries to convert the Fruit to some String representation by calling the toString() method on it. I think your Fruit class prints the same String no matter what's inside it. Try overriding the toString() method to get the correct results.

public class Fruit
{
    @Override
    public String toString()
    {
        return this.getName() + " " + this.getColor() + " " + this.getMass();
    }
}

Upvotes: 3

Related Questions