我的编码课有一个作业,我已经完成了大部分,但我不知道最后一部分该怎么做。
这是作业“为植物苗木创建一个类Plant,它有五个与植物相关的属性:
Maximum Height in feet
Common name
Scientific name
Price
Whether or not it is fragile.为类Plant创建两个您自己选择的方法。允许用户从控制台创建设备对象。创建植物对象后,将该对象添加到植物的ArrayList中。
允许用户编辑有关已输入的工厂对象的任何信息。
...And可获得额外的10个积分!!允许用户查看按价格(从低到高)、学名(按属的字母排序)或常用名称(按第一个单词的第一个字母排序)排序的植物。分配是个人的。“
我的代码
class nursery{
private int height;
private String cName;
private String sName;
private int cost;
private boolean fragile;
public nursery(int height, String cName, String sName, int cost, boolean fragile)
{
this.height=height;
this.cName=cName;
this.sName=sName;
this.cost=cost;
this.fragile=fragile;
}
}
public class Nursery {
public static void main(String[] args) {
ArrayList<nursery> plant = new ArrayList<>();
Scanner s = new Scanner(System.in);
while(true){
//get the plant varibles
System.out.println("Enter the common name of the plant: ");
String cName = s.next();
System.out.println("Enter the scientific name of the plant: ");
String sName = s.next();
System.out.println("Enter the height of the plant: ");
int height = s.nextInt();
System.out.println("Enter whether the plant is fragile or not: ");
boolean fragile =s.nextBoolean();
System.out.println("Enter the price of the plant: ");
int cost=s.nextInt();
//add to the arraylist
nursery Plant = new nursery(height, cName, sName, cost, fragile);
plant.add(Plant);
System.out.println("If u would like to stop entering press q.");
String quit = s.next();
//quit out if wanted
if(quit.equals("q")||quit.equals("Q"))
break;
}
}
}我不知道如何做的是“允许用户编辑关于已经输入的工厂对象的任何信息”。我试过搜索,但一直找不到答案。
发布于 2015-01-30 23:50:12
您已经将所有的行星对象( nursery )保留到ArrayList<nursery> plant,所以您需要做的就是从列表中找到它并重置它的值。
一般的示例可能如下所示:
nursery plant_to_update = null;
for (int i=0; i<plant.length; i++){
current_plant = plant.get(i);
// say user want to update planet with cName as 'planet 1'
if(plan_to_update.cName == "planet 1"){
plant_to_update = current_plant;
break;
}
}
if( plant_to_update != null){
// update planet 1 with new value
plant_to_update.setHeight(50);
plant_to_update.setCost(60);
}并且,在nursery类中添加setter以更新这些私有成员
public void setHeight(int height){
this.height = height;
}
public void setCost(int cost){
this.cost = cost;
}https://stackoverflow.com/questions/28239412
复制相似问题