Given a base Plant class and a derived Flower class, complete main() to create an ArrayList called myGarden. The ArrayList should be able to store objects that belong to the Plant class or the Flower class. Create a method called printArrayList(), that uses the printInfo() methods defined in the respective classes and prints each element in myGarden. The program should read plants or flowers from input (ending with -1), adding each Plant or Flower to the myGarden ArrayList, and output each element in myGarden using the printInfo() method.

Respuesta :

Answer:

See explaination

Explanation:

import java.util.Scanner;

import java.util.ArrayList;

import java.util.StringTokenizer;

public class PlantArrayListExample{

public static void main(String[] args) {

Scanner scnr = new Scanner(System.in);

String input;

ArrayList<Plant> myGarden = new ArrayList<Plant>();

String plantName, colorOfFlowers;

boolean isAnnual;

double plantCost;

input = scnr.next();

Plant temp = null;

while(!input.equals("-1")){

plantName = scnr.next();

plantCost = scnr.nextDouble();

if(input.equals("flower")){

isAnnual = scnr.next().equals("true");

colorOfFlowers = scnr.next();

temp = new Flower();

temp.setPlantName(plantName);

temp.setPlantCost(plantCost);

((Flower)temp).setPlantType(isAnnual);

((Flower)temp).setColorOfFlowers(colorOfFlowers);

myGarden.add(temp);

}

else{

temp = new Plant();

temp.setPlantName(plantName);

temp.setPlantCost(plantCost);

myGarden.add(temp);

}

input = scnr.next();

}

printArrayList(myGarden);

}

public static <T extends Plant> void printArrayList(ArrayList<T> myGarden){

for(Plant p:myGarden){

System.out.println(p);

}

}

}

Q&A Education