I creating a program to emulate a restaurant bill, this contains two classes, Diner and Food Item.
Item class:
package dinersbill;
public class Item {
private String name;
private double price;
private int buyerCount = 0;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() {
return name;
}
public double getPrice() {
return price;
}
public int getBuyerCount() {
return buyerCount;
}
public void incrementBuyerCount() {
buyerCount += 1;
}
}
Diner class:
package dinersbill;
import java.util.ArrayList;
public class Diner {
private String name;
private ArrayList<Item> itemList = new ArrayList<Item>();
public Diner(String name) {
this.name = name;
}
public String getName() {
return name;
}
public ArrayList<Item> getItemList() {
return itemList;
}
public void addItem(Item foodItem) {
itemList.add(foodItem);
foodItem.incrementBuyerCount();
}
public double getPrice() {
double total = 0;
for(Item item : itemList) {
total += item.getPrice() / item.getBuyerCount();
}
return total;
}
}
The Diner class holds an ArrayList of Item objects, as one Diner may purchase multiple Items. Finally, I have the top level class which holds an ArrayList of Diner objects:
package dinersbill;
import java.util.ArrayList;
public class DinerList {
private ArrayList<Diner> diners = new ArrayList<Diner>();
public DinerList(ArrayList<Diner> diners) {
this.diners = diners;
}
public ArrayList<Item> getDinerItems() {
ArrayList<Item> itemList = new ArrayList<>();
for(Diner d : diners) {
for(Item i : d.getItemList()) itemList.add(i);
}
return itemList;
}
}
How would I go about altering the getDinerItems method in DinerList to only return objects if they appear once? I am having an issue with Items appearing more than once in this list as a single item may be purchased by multiple Diners.
For example:
private static DinerList diners = new DinerList(dinerList);
public static void main(String[] args) {
Diner diner1 = new Diner("John");
Diner diner2 = new Diner("Tom");
dinerList.add(diner1);
dinerList.add(diner2);
Item item1 = new Item("Pizza", 5);
Item item2 = new Item("Icecream", 10);
diner1.addItem(item1);
diner2.addItem(item1);
diner2.addItem(item2);
for(Item i : diners.getDinerItems()) {
System.out.println(i.getName());
}
}
Actual Output:
Pizza Icecream Pizza
The Output I would like:
Pizza Icecream
getDinerItems()should do? Should it return a collection of items where a given item only appears once (with varying "buyer counts") or should it only return the items that appear once in all diners' item lists? The latter is what your question is actually implying (which does not make sense really).