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;
}
}