Question

In: Computer Science

Write in Java * Create a new client class called Plants.java * Write code in the...

Write in Java

* Create a new client class called Plants.java

* Write code in the Plants class that solves problems 1,2,3 and 4

* Include the solutions of the different problems in different methods and call them from the main method

* Use the BagInterface.java and ArrayBag.java, but do not add any code

Problem 1: Create a bag plantsCart, which holds the following spring seedlings(represented by String) Rose, Daisy, Cabbage, Cucumber, Carrot, Cucumber, Daffodil, Daisy, Rose, Iris, Rose, Spinach.

Problem 2: Given the bag plantsCart, write statements that remove and display all plants in the bag

Probelm 3: Write statements that remove and count all occurnace of the string Rose in plantsCart. Do not remoe any other strings from the bag. Report the number of time that Rose occured. Print the new content of plantCarts.

Problem 4: Write a code fragment that moves all flowers from plantCart to a new cart (a new bag of Srtring objects) - flowersCart. At the end, report the numbers of flowers in flowersCart.

HINT: You can create a bag called flowers, which contains the strings representing flowers used in this program: Daisy, Iris, Rose, Daffodil and then use it to check each plant from plantsCart, whether it is a flower or not.

************************************************************************************

**BagInterface.java code**

_____________________________________
public interface BagInterface<T> {

/** Gets the current number of entries in this bag.
@return the integer number of entries currently in the bag */
public int getCurrentSize();

/** Sees whether this bag is full.
@return true if the bag is full, or false if not */
public boolean isFull();

/** Sees whether this bag is empty.
@return true if the bag is empty, or false if not */
public boolean isEmpty();

/** Adds a new entry to this bag.
@param newEntry the object to be added as a new entry
@return true if the addition is successful, or false if not */
public boolean add(T newEntry);

/** Removes one unspecified entry from this bag, if possible.
@return either the removed entry, if the removal
was successful, or null */
public T remove();

/** Removes one occurrence of a given entry from this bag,
if possible.
@param anEntry the entry to be removed
@return true if the removal was successful, or false if not */
public boolean remove(T anEntry);

/** Removes all entries from this bag. */
public void clear();

/** Counts the number of times a given entry appears in this bag.
@param anEntry the entry to be counted
@return the number of times anEntry appears in the bag */
public int getFrequencyOf(T anEntry);

/** Tests whether this bag contains a given entry.
@param anEntry the entry to locate
@return true if the bag contains anEntry, or false otherwise */
public boolean contains(T anEntry);

/** Creates an array of all entries that are in this bag.
@return a newly allocated array of all the entries in the bag */
public T[] toArray();
  
/** Overrides the toString method to give a nice display of the items in
   * the bag in this format Bag{Size:# <1> <2> <3> <4> }
* @return a string representation of the contents of the bag */
public String toString();
  
   /** Test whether this bag is equal to a given (as parameter) bag.
   @param aBag the bag to be compare to
@return true if both bags are equal */
   public boolean equals(ArrayBag<T> aBag)
  
} // end BagInterface


*******************************************************************

***ArrayBag.java code *******

______________________________________________

//Start of ArrayBag class


public class ArrayBag<T> implements BagInterface<T> {

private final T[] bag;
private static final int DEFAULT_CAPACITY = 25;
private int numberOfEntries;

/** Creates an empty bag whose initial capacity is 25. */
public ArrayBag() {
this(DEFAULT_CAPACITY);
} // end default constructor

/** Creates an empty bag having a given initial capacity.
@param capacity the integer capacity desired */
public ArrayBag(int capacity) {
numberOfEntries = 0;

// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] tempBag = (T[]) new Object[capacity]; // unchecked cast
bag = tempBag;
} // end constructor


public boolean add(T newEntry) {
boolean result = true;
if (isFull()) {
result = false;
} else { // assertion: result is true here
bag[numberOfEntries] = newEntry;
numberOfEntries++;
} // end if
return result;
} // end add

/** Retrieves all entries that are in this bag.
@return a newly allocated array of all the entries in the bag */
public T[] toArray() {

// the cast is safe because the new array contains null entries
@SuppressWarnings("unchecked")
T[] result = (T[]) new Object[numberOfEntries]; // unchecked cast
for (int index = 0; index < numberOfEntries; index++) {
result[index] = bag[index];
} // end for
return result;
} // end toArray

/** Sees whether this bag is full.
@return true if the bag is full, or false if not */
public boolean isFull() {
return numberOfEntries == bag.length;
} // end isFull

/** Sees whether this bag is empty.
@return true if the bag is empty, or false if not */
public boolean isEmpty() {
return numberOfEntries == 0;
} // end isEmpty

/** Gets the current number of entries in this bag.
@return the integer number of entries currently in the bag */
public int getCurrentSize() {
return numberOfEntries;
} // end getCurrentSize


public int getFrequencyOf(T anEntry) {
int counter = 0;
for (int index = 0; index < numberOfEntries; index++) {
if (anEntry.equals(bag[index])) {
counter++;
} // end if
} // end for
return counter;
} // end getFrequencyOf

/** Tests whether this bag contains a given entry.
@param anEntry the entry to locate
@return true if the bag contains anEntry, or false otherwise */
public boolean contains(T anEntry) {
return getIndexOf(anEntry) > -1;
} // end contains

/** Removes all entries from this bag. */
public void clear() {
while (!isEmpty()) {
remove();
}
} // end clear

/** Removes one unspecified entry from this bag, if possible.
@return either the removed entry, if the removal was successful,
or null otherwise */
public T remove() {
T result = null;

if (numberOfEntries > 0) {
numberOfEntries--;
result = bag[numberOfEntries];
bag[numberOfEntries] = null;
} // end if


return result;
} // end remove

/** Removes one occurrence of a given entry from this bag.
@param anEntry the entry to be removed
@return true if the removal was successful, or false if not */
public boolean remove(T anEntry) {
int index = getIndexOf(anEntry);
T result = removeEntry(index);
return anEntry.equals(result);
} // end remove


private T removeEntry(int givenIndex) {
T result = null;
if (!isEmpty() && (givenIndex >= 0)) {
result = bag[givenIndex]; // entry to remove
numberOfEntries--;
bag[givenIndex] = bag[numberOfEntries]; // replace entry with last entry
bag[numberOfEntries] = null; // remove last entry
} // end if
return result;
} // end removeEntry


private int getIndexOf(T anEntry) {
int where = -1;
boolean found = false;
for (int index = 0; !found && (index < numberOfEntries); index++) {
if (anEntry.equals(bag[index])) {
found = true;
where = index;
} // end if
} // end for
} // end getIndexOf


public String toString() {

String result = "Bag{Size:" + numberOfEntries + " ";
for (int index = 0; index < numberOfEntries; index++) {
result += "<" + bag[index] + "> ";
} // end for

result += "}";
return result;
}

   public boolean equals(ArrayBag<T> aBag) {
         
boolean result = false; // result of comparison of bags
int position; // want position available throughout method

if (numberOfEntries == aBag.getCurrentSize()) {
// Provisionally these are the same
result = true;
for (position = 0; (position < numberOfEntries); position++) {
// Get the frequency of the item in this bag
int countInThisBag = getFrequencyOf(bag[position]);

int countInOtherBag = aBag.getFrequencyOf(bag[position]);

if (countInThisBag != countInOtherBag) {
result = false }
} // end for
}
return result;
} // end equals
} // end ArrayBag

Solutions

Expert Solution

public clss Plants extends ArrayBag {
   public static void main(String []args) throws IOException {
      
       Array list = ["rose", "daisy", "cabbage", "cucumber", "carrot", "cucumber", "daffodil", "daisy", "rose", "iris", "rose", "spinach"];
       ArrayBag plantsCart = create(list);
       deleteAndDisplay(plantsCart);
       ArrayBag plantsCart = create(list);
       removeRose(plantsCart);
       ArrayBag plantsCart = create(list);
       Array flower = ["rose", "daisy", "daffodil", "iris"];
       ArrayBag flowers = create(flower);
       createFlowersCart(plantsCart, flowers);
      
   }
   ArrayBag create(Array list) {
       ArrayBag plantsCart = new ArrayBag();
       for(String element : list) {
           plantsCart.add(element);          
       }
       return plantsCart;
   }
  
   void deleteAndDisplay(ArrayBag plantsCart) {
       while(!plantsCart.isEmpty)
           System.out.println(plantsCart.remove());
   }

   void removeRose(ArrayBag plantsCart) {
       System.out.println("Frequency of Rose:"+plantsCart.getFrequencyOf("rose")+"\n";
       while(plantsCart.remove("rose"));
       plantsCart = plantsCart.toArray();
       for(ArrayBag element : plantsCart) {
           System.out.println(element);
       }
   }
   void createFlowersCart(ArrayBag plantsCart, ArrayBag flowers){
       ArrayBag flowersCart = new ArrayBag();
       int c = 0;
       plantsCart = plantsCart.toArray();
       for(ArrayBag element : plantsCart) {
           if(flowers.contains(element)) {
               c++;
               flowersCart.add(element);
               ArrayBag.remove(element);
           }
       }
       System.out.println("No. of flowers in FlowerCart:"+c);
   }
}


Related Solutions

In Java Create a class called "TestZoo" that holds your main method. Write the code in...
In Java Create a class called "TestZoo" that holds your main method. Write the code in main to create a number of instances of the objects. Create a number of animals and assign a cage and a diet to each. Use a string to specify the diet. Create a zoo object and populate it with your animals. Declare the Animal object in zoo as Animal[] animal = new Animal[3] and add the animals into this array. Note that this zoo...
LANGUAGE: JAVA Create a New Project called YourLastNameDomainName. Write a DomainName class that encapsulates the concept...
LANGUAGE: JAVA Create a New Project called YourLastNameDomainName. Write a DomainName class that encapsulates the concept of a domain name, assuming a domain name has a single attribute: the domain name itself. Include the following: - Constructor: accepts the domain name as an argument. - getDomain: an accessor method for the domain name field. - setDomain: a mutator method for the domain name field. - prefix: a method returning whether or not the domain name starts with www. - extension:...
Create a Java project called Lab3B and a class named Lab3B. Create a second new class...
Create a Java project called Lab3B and a class named Lab3B. Create a second new class named Book. In the Book class: Add the following private instance variables: title (String) author (String) rating (int) Add a constructor that receives 3 parameters (one for each instance variable) and sets each instance variable equal to the corresponding variable. Add a second constructor that receives only 2 String parameters, inTitle and inAuthor. This constructor should only assign input parameter values to title and...
Create a Java project called Lab3A and a class named Lab3A. Create a second new class...
Create a Java project called Lab3A and a class named Lab3A. Create a second new class named Employee. In the Employee class: Add the following private instance variables: name (String) job (String) salary (double) Add a constructor that receives 3 parameters (one for each instance variable) and sets each instance variable equal to the corresponding variable. (Refer to the Tutorial3 program constructor if needed to remember how to do this.) Add a public String method named getName (no parameter) that...
Create a Java project called 5 and a class named 5 Create a second new class...
Create a Java project called 5 and a class named 5 Create a second new class named CoinFlipper Add 2 int instance variables named headsCount and tailsCount Add a constructor with no parameters that sets both instance variables to 0; Add a public int method named flipCoin (no parameters). It should generate a random number between 0 & 1 and return that number. (Important note: put the Random randomNumbers = new Random(); statement before all the methods, just under the...
Create a new Java project called lab1 and a class named Lab1 Create a second class...
Create a new Java project called lab1 and a class named Lab1 Create a second class called VolumeCalculator. Add a static field named PI which = 1415 Add the following static methods: double static method named sphere that receives 1 double parameter (radius) and returns the volume of a sphere. double static method named cylinder that receives 2 double parameters (radius & height) and returns the volume of a cylinder. double static method named cube that receives 1 double parameter...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called...
android studio -Starting with a basic activity, create a new Java class (use File->New->Java class) called DataBaseManager as in Lecture 5 and create a database table in SQLite, called StudentInfo. The fields for the StudentInfo table include StudentID, FirstName, LastName, YearOfBirth and Gender. Include functions for adding a row to the table and for retrieving all rows, similar to that shown in lecture 5. No user interface is required for this question, t -Continuing from , follow the example in...
1. Create a new Java project called L2 and a class named L2 2. Create a...
1. Create a new Java project called L2 and a class named L2 2. Create a second class called ArrayExaminer. 3. In the ArrayExaminer class declare the following instance variables: a. String named textFileName b. Array of 20 integers named numArray (Only do the 1st half of the declaration here: int [] numArray; ) c. Integer variable named largest d. Integer value named largestIndex 4. Add the following methods to this class: a. A constructor with one String parameter that...
Step 1: Create a new Java project called Lab5.5. Step 2: Now create a new class...
Step 1: Create a new Java project called Lab5.5. Step 2: Now create a new class called aDLLNode. class aDLLNode { aDLLNode prev;    char data;    aDLLNode next; aDLLNode(char mydata) { // Constructor data = mydata; next = null;    prev = null;    } }; Step 3: In the main() function of the driver class (Lab5.5), instantiate an object of type aDLLNode and print the content of its class public static void main(String[] args) { System.out.println("-----------------------------------------");    System.out.println("--------Create...
java code: Problem 1: Create a class called Elevator that can be moved between floors in...
java code: Problem 1: Create a class called Elevator that can be moved between floors in an N-storey building. Elevator uses a constructor to initialize the number of floors (N) in the building when the object is instantiated. Elevator also has a default constructor that creates a five storey building. The Elevator class has a termination condition that requires the elevator to be moved to the main (i.e., first) floor when the object is cleaned up. Write a finalize() method...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT