Page 1 of 1

Plant information (ArrayList): Given a base Plant class and a derived Flower class, complete main() to create an ArrayLi

Posted: Fri Jul 08, 2022 6:43 am
by answerhappygod
Plant information (ArrayList):
Given a base Plant class and a derived Flower class, completemain() to create an ArrayList called myGarden. The ArrayList shouldbe able to store objects that belong to the Plant class or theFlower class. Create a method called printArrayList(), that usesthe printInfo() methods defined in the respective classes andprints each element in myGarden. The program should read plants orflowers from input (ending with -1), add each Plant or Flower tothe myGarden ArrayList, and output each element in myGarden usingthe printInfo() method.
Ex. If the input is:
the output is:
import java.util.Scanner;import java.util.ArrayList;import java.util.StringTokenizer;
PlantArrayListExample.java
public class PlantArrayListExample {
// TODO: Define a printArrayList method that printsan ArrayList of plant (or flower) objects public static void main(String[] args) { Scanner scnr = new Scanner(System.in); String input; // TODO: Declare an ArrayList called myGardenthat can hold object of type plant
// TODO: Declare variables - plantName,plantCost, colorOfFlowers, isAnnual input = scnr.next(); while(!input.equals("-1")){ // TODO: Check if input is aplant or flower // Store asa plant object or flower object // Add tothe ArrayList myGarden input = scnr.next(); } // TODO: Call the method printArrayList toprint myGarden }}
Plant.java
public class Plant { protected String plantName; protected String plantCost;
public void setPlantName(String userPlantName){ plantName = userPlantName; }
public String getPlantName() { return plantName; }
public void setPlantCost(String userPlantCost){ plantCost = userPlantCost; }
public String getPlantCost() { return plantCost; }
public void printInfo() { System.out.println("Plant Information:"); System.out.println(" Plant name: " +plantName); System.out.println(" Cost: " +plantCost); }}
Flower.java
public class Flower extends Plant {
private boolean isAnnual; private String colorOfFlowers;
public void setPlantType(boolean userIsAnnual){ isAnnual = userIsAnnual; }
public boolean getPlantType(){ return isAnnual; }
public void setColorOfFlowers(StringuserColorOfFlowers) { colorOfFlowers = userColorOfFlowers; }
public String getColorOfFlowers(){ return colorOfFlowers; } @Override public void printInfo(){ System.out.println("Plant Information:"); System.out.println(" Plant name: " +plantName); System.out.println(" Cost: " +plantCost); System.out.println(" Annual: " +isAnnual); System.out.println(" Color of flowers:" + colorOfFlowers); }}