Implement a class Bag that stores items represented as strings. Items can be rep
ID: 3549855 • Letter: I
Question
Implement a class Bag that stores items represented as strings. Items can be repeated.
Supply methods for adding an item, and for counting how many times an item has
been added:
public void add(String itemName)
public int count(String itemName)
Your Bag class should store the data in an ArrayList<Item>, where Item is an inner class
with two instance variables: the name of the item and the quantity.
we've been learning about interfaces recently so that would probably be appropriate to use here :)
Explanation / Answer
since your program doesn't clearly tells how to implement the interface, I've used my own very simple implementation
package com.chegg;
import java.util.ArrayList;
public class Bag implements BagInterface{
public class Item{
String itemName;
int quantity;
}
Item item;
ArrayList<Item> items = new ArrayList<Item>();
public void addItem(String itemName){
item = new Item();
item.itemName = itemName;
items.add(item);
}
public int count(String itemName){
int count=0;
for(Item item: items){
if(itemName.equalsIgnoreCase(item.itemName))
count++;
}
return count;
}
public static void main(String[] args){
BagInterface bag = new Bag();
bag.addItem("ball");
bag.addItem("ball");
bag.addItem("ball");
bag.addItem("ball");
bag.addItem("apple");
bag.addItem("apple");
bag.addItem("orange");
bag.addItem("orange");
bag.addItem("orange");
System.out.println("Count of ball::"+bag.count("ball"));
System.out.println("Count of apple::"+bag.count("apple"));
System.out.println("Count of orange::"+bag.count("orange"));
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.