我有一个学校作业,要求我将未知数量的类“水果”实例添加到数组列表“篮子”中并打印出每个水果对象的详细信息,我的代码将水果添加到数组列表中,但似乎覆盖每次上一个条目都给我留下了同一个项目的数组列表。到目前为止,这是我的代码:
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;
}
}