required boolean found no arguments [duplicate] - java

This question already has answers here:
required: double [] found: no arguments
(4 answers)
Closed 6 years ago.
hoping to find a solution before i put my head through my monitor.
What I am trying to do is use a boolean to make a sell function.
basically I want it not to sell stock if there is less than 0 (print error message)
if there is i want to +1 to numSold and -1 to numInStock.
when i try im getting an error
"method sellCopy in class item cannot be applied to given types; required boolean; found no arguments reason actual and formal argument list differ in length"
public abstract class Item
{
private String name;
private double price;
private int numInStock;
private int numSold;
public Item(String inName, double inPrice)
{
name = inName;
price = inPrice;
numInStock = 0;
numSold = 0;
}
public String getName()
{
return name;
}
public double getPrice()
{
return price;
}
public int getNuminStock()
{
return numInStock;
}
public int getNumSold()
{
return numSold;
}
public void receiveStock(int amount)
{
numInStock = numInStock + amount;
}
public boolean sellCopy(boolean sellCopy)
{
if (numInStock <= 0)
{
sellCopy = true;
numSold = numSold +1;
numInStock = numInStock -1;
return true;
}
else
{
sellCopy = false;
System.out.println("Stock unavalable");
return false;
}
}
}
public class Game extends Item
{
private int MaxPlayers;
public Game(String inName, int inMaxPlayers, double inPrice)
{
super(inName, inPrice);
MaxPlayers = inMaxPlayers;
}
public String toString()
{
return " Game " + super.toString() + " Maximum Player: " + MaxPlayers + "\n";
}
import java.util.*;
public class Shop
{
private ArrayList<Item> items = new ArrayList<Item>();
public boolean addItem(Item newItem)
{
if (!findItem(newItem.getName()))
{
items.add(newItem);
return true;
}
else
{
System.out.println(" Error - an item with that name " +newItem.getName() + " already exists");
return false;
}
}
public boolean findItem(String searchName)
{
for (Item nextItem : items)
{
//might be searchName//
if (searchName.equals(nextItem.getName()))
{
System.out.println(nextItem);
return true;
}
}
return false;
}
public void listItems()
{
System.out.println("The shop contains the following items***\n");
for (Item nextItem : items)
{
System.out.println(nextItem);
}
}
public void calcTotalSales()
{
double total = 0;
for (Item nextItem : items)
{
total += nextItem.getNumSold() * nextItem.getPrice();
}
System.out.println("****The total number sold is worth $" + total);
System.out.println("****");
}
}
public class test
{
public static void main (String args[])
{
//create the shop
Shop myShop = new Shop();
//create a Game and add it to the shop
Game game1 = new Game("Chess", 2, 39.95);
myShop.addItem(game1);
//order and get stock
game1.receiveStock(5);
//sell some items
game1.sellCopy();
//the bastard right here//
//print information about shop
myShop.calcTotalSales();
//test error conditions
Game game2 = new Game("Chess", 2, 39.95);
myShop.addItem(game2); //should fail as a Chess item is already in the shop
//eg2.sellCopy();
}
}

If you look at the code,
game1.sellCopy();
That sellCopy method needs a boolean. You need to pass it.
game1.sellCopy(true);// for example. Pass your actual value.

Related

How to merge two alike items within the ArrayList?

So, I have 1 superclass DessertItem. Which has 4 subclasses Candy, Cookie, Ice Cream, Sundae. The Sundae class extends the Ice Cream class. Superclass is an abstract class. I also have a separate class which does not belong to the superclass, but in the same package - Order. There is another class - DessertShop, where the main is located.
Candy, Cookie classes implement SameItem<> generic class. The generic interface SameItem<> class looks like this:
public interface SameItem<T> {
public boolean isSameAs(T other);
}
The Candy, Cookie classes have this method:
#Override
public boolean isSameAs(Candy other) {
if(this.getName() == other.getName() && this.getPricePerPound() == other.getPricePerPound()) {
return true;
}
else {
return false;
}
}
And something similar, but for the cookie class.
All the subclasses have these methods :
default constructor,
public Cookie(String n, int q, double p) {
super(n);
super.setPackaging("Box");
cookieQty = q;
pricePerDozen = p;
}
public int getCookieQty() {
return cookieQty;
}
public double getPricePerDozen() {
return pricePerDozen;
}
public void setCookieQty(int q) {
cookieQty = q;
}
public void setToppingPricePricePerDozen(double p) {
pricePerDozen = p;
}
#Override
public double calculateCost() {
double cookieCost = cookieQty * (pricePerDozen/12);
return cookieCost;
}
and toString() method
So, what my program does is gets the input from the User, asks the name of the dessert, asks the quantity, or the quantity according to the dessert, ask the unit price. Asks the payment method. And then prints the receipt. This how the Order class looks like:
import java.util.ArrayList;
import java.util.List;
public class Order extends implements Payable{
//attributes
PayType payMethod;
private ArrayList<DessertItem> OrderArray;
//Constructor
public Order() {
OrderArray = new ArrayList<>();
payMethod = PayType.CASH;
}
//methods
public ArrayList<DessertItem> getOrderList(){
return OrderArray;
}// end of getOrderList
public ArrayList<DessertItem> Add(DessertItem addDesert){
enter code here
OrderArray.add(addDesert);
/* for(DessertItem i : getOrderList()) {
if(i instanceof Candy) {
for(DessertItem j : getOrderList()) {
if(j instanceof Candy) {
if(((Candy) i).isSameAs((Candy) j)) {
*/
//this is what I have tried so far, but I am lost
}
}
}
} else if(i instanceof Cookie) {
for (DessertItem j : getOrderList()) {
if(((Cookie) i).isSameAs((Cookie)j)) {
OrderArray.add(j);
} else {
OrderArray.add(i);
}
}
}
}
return OrderArray;
}// end of Add
public int itemCount(){
int counted = OrderArray.size();
return counted;
}//end of itemCount
public double orderCost() {
double orderResult = 0;
for(int i=0; i<OrderArray.size(); i++) {
orderResult = orderResult + OrderArray.get(i).calculateCost();
}
return orderResult;
}
public double orderTax() {
double taxResult = 0;
for(int i = 0; i<OrderArray.size(); i++) {
taxResult = taxResult + OrderArray.get(i).calculateTax();
}
return taxResult;
}
public double orderTotal() {
double ordertotal = orderTax() + orderCost();
return ordertotal;
}
#Override
public PayType getType() {
// TODO Auto-generated method stub
return payMethod;
}
#Override
public void setPayType(PayType p) {
payMethod = p;
}
public String toString() {
String finalOutput = "";
finalOutput += "------------------------Receipt--------------------------\n";
for(int i = 0; i < OrderArray.size(); i++) {
finalOutput = finalOutput + OrderArray.get(i).toString();
}
finalOutput += "--------------------------------------------------\n";
String line2 = "Total Number of items in order: " + itemCount() + "\n";
String line3 = String.format("Order Subtotals:\t\t\t\t $%-6.2f", orderCost());
String line4 = String.format("[Tax: $%.2f]\n", orderTax());
String line5 = String.format("\nOrder Total:\t\t\t\t\t $%-6.2f\n", orderTotal());
String outputVar = String.format("%s\n%s%s%17s", line2, line3, line4, line5);
String ending = "----------------------------------------------------";
String payType = String.format("\nPaid for with: %s", payMethod.name());
return finalOutput + outputVar + ending + payType;
}
So, my question is, how can I combine like items into one item?

JOptionPane not displaying all items from ArrayList

I am trying to write a program that will create a food order consisting of food items displayed from a menu. Each item is selected and given a certain quantity. I want to display the items that I select in a JTextField but it has not been working correctly.
There are a few problems that I have ran into and cannot seem to figure out,
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
The following is my are all of my class files.
import java.util.ArrayList;
public class Menu {
private final ArrayList<Item> menu;
public Menu() {
menu = new ArrayList<>();
}
public void addItem(Item item) {
menu.add(item);
}
public Item getItem(int itemNo) {
if (menu.size() > itemNo) {
return menu.get(itemNo);
}
return null;
}
#Override
public String toString() {
for (int i = 0; i < menu.size(); i++) {
return String.format("%s: %s \n",i+1, menu.get(i));
}
return null;
}
}
public class Item {
private final String name;
private final double price;
public Item(String name, double price) {
this.name = name;
this.price = price;
}
public double getPrice() {
return price;
}
#Override
public String toString() {
return String.format("Name %s # Price $%s", name, price);
}
public boolean equals(Item item) {
return item.name.equals(item.name);
}
}
public class ItemQty {
private final Item item;
private final int quantity;
public ItemQty(Item item, int quantity) {
this.item = item;
this.quantity = quantity;
}
public Item getItem() {
return item;
}
public int getQuantity() {
return quantity;
}
#Override
public String toString() {
return String.format("%s - %s\n", quantity, item);
}
public boolean equals(ItemQty itemQty) {
return itemQty.getItem().equals(itemQty.getItem());
}
}
import java.util.ArrayList;
public class Order {
private final ArrayList<ItemQty> order;
public Order() {
order = new ArrayList<>();
}
public void addToOrder(ItemQty itemQty) {
if (order.contains(itemQty)) {
int amount = itemQty.getQuantity();
amount += 1;
}
else
order.add(itemQty);
}
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
#Override
public String toString() {
String str = "";
for (int index = 0; index < order.size(); index++) {
str += order.get(index).toString() + "\n\n";
}
return str;
}
}
Any help or critiques would be appreciated
My getTotalPrice method is not properly calculating the cost and I'm not entirely sure why.
This is due to the fact that you're returning the value of sum only after the first iteration of your loop
public double getTotalPrice() {
for (int index = 0; index < order.size(); index++) {
double price = order.get(index).getItem().getPrice();
int quantity = order.get(index).getQuantity();
double sum = price * quantity;
return sum;
}
return 0;
}
Something like...
public double getTotalPrice() {
double sum = 0;
for (Order item : order) {
double price = item.getItem().getPrice();
int quantity = item.getQuantity();
sum += (price * quantity);
}
return sum;
}
would work better
The JOptionPane is supposed to display all of the items that I added to the deli arraylist, but it only displays the first one which is Nachos.
Since there is no JOptionPane in your code, it's impossible to know what the issue might be
I want the program to determine if an item is already present in the Arraylist and add to the quantity if it does, and if not then add a new entry to the arraylist. However, it always adds a new item, regardless of if it exists already.
Okay, this is a lot more difficult, because you code doesn't really provide enough support to do it.
There's no way for your code to update the quantity information after the ItemQty is created, you will need to supply a setter of some kind to perform this action (or a add method, to which you pass another ItemQty and it does the job for you)
First, I'd add a new method to ItemQty
public class ItemQty {
//...
public void add(int quantity) {
this.quantity += quantity;
}
}
This just makes it possible to increase the quantity.
Second, I'd change the Order#addToOrder, I'd make it so you had to pass an Item and a quantity to it (other classes don't need to make a ItemQty object in this case). In this method, I'd search for a matching item and either update it or add it to the order.
public class Order {
//...
public void addToOrder(Item item, int quantity) {
List<ItemQty> matches = order.stream().filter((itemQty) -> {
return itemQty.getItem().equals(item);
}).collect(Collectors.toList());
if (matches.size() > 0) {
matches.get(0).add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}
Okay, that might have you scratching your head, it does me, but basically, it's just a fancy pancy way for saying...
public void addToOrder(Item item, int quantity) {
ItemQty match = null;
for (ItemQty check : order) {
if (check.getItem().equals(item)) {
match = check;
break;
}
}
if (match != null) {
match.add(quantity);
} else {
order.add(new ItemQty(item, quantity));
}
}

ArrayList and Passing values

I am new to programming and we just learned ArrayLists in my class today and I have an easy question for you guys, I just can't seem to find it in the notes on what to set the passing value equal to. The point of this practice program is to take in a Number Object (that class has already been created) and those Numbers in the ArrayList are supposed to be counted as odds, evens, and perfect numbers. Here is the first couple of lines of the program which is all you should need.
import java.util.ArrayList;
import static java.lang.System.*;
public class NumberAnalyzer {
private ArrayList<Number> list;
public NumberAnalyzer() {
list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
}
public void setList(String numbers) {
}
What am I supposed to set (String numbers) to in both NumberAnalyzer() and setList()? Thanks in advance for answering a noob question!
NumberAnalyzer test = new NumberAnalyzer("5 12 9 6 1 4 8 6");
out.println(test);
out.println("odd count = "+test.countOdds());
out.println("even count = "+test.countEvens());
out.println("perfect count = "+test.countPerfects()+"\n\n\n");
This is the Lab16b Class that will run the program. ^^
public class Number
{
private Integer number;
public Number()
{
number = 0;
}
public Number(int num)
{
number = num;
}
public void setNumber(int num)
{
number = num;
}
public int getNumber()
{
return 0;
}
public boolean isOdd()
{
return number % 2 != 0;
}
public boolean isPerfect()
{
int total=0;
for(int i = 1; i < number; i++)
{
if(number % i == 0)
{
total = total + i;
}
}
if(total == number)
{
return true;
}
else
{
return false;
}
}
public String toString( )
{
return "";
}
}
Here is the Number class. ^^
Based on the information you provided, this is what I feel NumberAnalyzer should look like. The setList function is presently being used to take a String and add the numbers in it to a new list.
public class NumberAnalyzer {
private List<Number> list;
public NumberAnalyzer() {
this.list = new ArrayList<Number>();
}
public NumberAnalyzer(String numbers) {
setList(numbers);
}
public void setList(String numbers) {
String[] nums = numbers.split(" ");
this.list = new ArrayList<Number>();
for(String num: nums)
list.add(new Number(Integer.parseInt(num)));
}
}
Analyze to learn something.
public static void main(String[] args) {
String temp = "5 12 9 6 1 4 8 6";
NumberAnalyzer analyzer = new NumberAnalyzer(temp);
//foreach without lambda expressions
System.out.println("without Lambda");
for (NeverNumber i : analyzer.getList()) {
i.print();
}
//with the use of lambda expressions, which was introduced in Java 8
System.out.println("\nwith Lambda");
analyzer.getList().stream().forEach((noNumber) -> noNumber.print());
NeverNumber number = new NeverNumber(31);
number.print();
number.setNumber(1234);
number.print();
}
public class NumberAnalyzer {
private List<NeverNumber> list; //List is interface for ArrayList
public NumberAnalyzer(String numbers) {
String[] numb=numbers.split(" ");
this.list=new ArrayList<>();
for (String i : numb) {
list.add(new NeverNumber(Integer.parseInt(i)));
}
}
public void setList(List<NeverNumber> numbers) {
List<NeverNumber> copy=new ArrayList<>();
numbers.stream().forEach((i) -> {
copy.add(i.copy());
});
this.list=copy;
}
public List<NeverNumber> getList() {
List<NeverNumber> copy=new ArrayList<>();
this.list.stream().forEach((i) -> {
copy.add(i.copy());
});
return copy;
}
public NeverNumber getNumber(int index) {
return list.get(index).copy();
}
}
public class NeverNumber { //We do not use the names used in the standard library.
//In the library there is a class Number.
private int number; // If you can use simple types int instead of Integer.
public NeverNumber() {
number = 0;
}
public NeverNumber(int num) {
number = num;
}
private NeverNumber(NeverNumber nn) {
this.number=nn.number;
}
public void setNumber(int num) {
number = num;
}
public int getNumber() {
return this.number;
}
public boolean isOdd() {
return number % 2 != 0;
}
public boolean isPerfect() {
long end = Math.round(Math.sqrt(number)); //Method Math.sqrt(Number) returns a double, a method Math.round(double) returns long.
for (int i = 2; i < end + 1; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
public NeverNumber copy(){
return new NeverNumber(this);
}
public void print() {
System.out.println("for: " + this.toString() + " isPer: " + this.isPerfect() + " isOdd: " + this.isOdd() + "\n");
}
#Override //Every class in Java inherits from the Object class in which it is toString(),
//so we have to override our implementation.
public String toString() {
return this.number + ""; //The object of any class + "" creates a new object of the String class,
//that is for complex types, calls the toString () method implemented in this class,
//override the toString () from the Object class. If the runs, we miss class toString()
//calls from the Object class.
}
}

Removing an specific object from an arraylist

I need help removing a specific object from an arraylist. I'm creating objects with a unique ID and grade for each object.I'm trying to use this unique ID to remove an object from the arraylist, but am having trouble figuring out why my code isn't working. I have my main Driver class, a superclass, and a subclass.
The subclass is where the object information is passed from and extends the superclass. I thought that since the subclass is extended, it would be able to be defined from there.
The problem that is occurring is line 49 of the superclasss. Eclipse says that getStudentID isn't defined in the class.
I am trying to modify code that my instructor provided in order to locate this unique ID that an object in the arraylist has. I believe I did everything correctly, but the method "locationPerson" doesn't seem to see the getStudentID() method in the subclass.
Here is the code. Any help would be appreciated!
Subclass
public class StudentEnrollee extends ClassSection{
private int grade;
private String studentID;
StudentEnrollee() {
setStudentID("000-000");
setGrade(0);
}
StudentEnrollee(String ID, int theGrade) {
setStudentID(ID);
setGrade(0);
}
//STUDENT ID
public String getStudentID() {
return studentID;
}
public void setStudentID(String theStudentID) {
this.studentID = theStudentID;
}
//STUDENT GRADE
public int getGrade() {
return grade;
}
public void setGrade(int studentGrade) {
this.grade = studentGrade;
}
public String toString() {
return("Student ID : " + studentID + "\n" +
"Student Grade: " + grade);
}
}
Superclass
import java.util.ArrayList;
import java.util.List;
public class ClassSection {
private int crn, courseNumber, capacity, enrollment, ID, student;
private String departmentCode, courseMode, meetingDay, meetingTime;
//CONSTRUCTOR
ClassSection() {
setCrn(0);
setDepartmentCode("");
setCourseNumber(0);
setCourseMode("");
setMeetingDay("");
setMeetingTime("");
setCapacity(0);
setEnrollment(0);
setID(0);
}
ClassSection(int crn, String departmentCode, int courseNumber, String courseMode, String meetingDay, String meetingTime, int capacity, int enrollment, int ID) {
setCrn(crn);
setDepartmentCode(departmentCode);
setCourseNumber(courseNumber);
setCourseMode(courseMode);
setMeetingDay(meetingDay);
setMeetingTime(meetingTime);
setCapacity(capacity);
setEnrollment(enrollment);
setID(ID);
}
//STUDENT ENROLL ARRAY
List < StudentEnrollee > studentList = new ArrayList < StudentEnrollee > ();
public int getStudent() {
return student;
}
public void addStudent(StudentEnrollee studentObject) {
studentList.add(studentObject);
}
//LOCATING PERSON
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
//Delete person
public void deletePerson(String studentID) {
ClassSection personObject = locatePerson(studentID); // we'll use our locatePerson method find the index of a Person with a given socSecNum.
if (personObject != null) studentList.remove(personObject); // if element i contains the target SSN, remove it.
}
//DISPLAY LIST OF ENROLLEE
public void displayListV1() {
for (int i = 0; i < studentList.size(); i++) // the old way
{
System.out.println(studentList.get(i) + "\n");
}
}
//CRN
public int getCrn() {
return crn;
}
void setCrn(int classCrn) {
this.crn = classCrn;
}
//DEPARTMENT CODE
public String getDepartmentCode() {
return departmentCode;
}
void setDepartmentCode(String classDepartmentCode) {
this.departmentCode = classDepartmentCode;
}
//COURSE NUMBER
public int getCourseNumber() {
return courseNumber;
}
void setCourseNumber(int classCourseNumber) {
this.courseNumber = classCourseNumber;
}
//COURSE LOCATION
public String getCourseMode() {
return courseMode;
}
public void setCourseMode(String classCourseMode) {
this.courseMode = classCourseMode;
}
//MEETING DAY
public String getMeetingDay() {
return meetingDay;
}
public void setMeetingDay(String classMeetingDay) {
this.meetingDay = classMeetingDay;
}
//MEETING TIMES
public String getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(String classMeetingTime) {
this.meetingTime = classMeetingTime;
}
//CAPACITY
public int getCapacity() {
return capacity;
}
public void setCapacity(int classCapacity) {
this.capacity = classCapacity;
}
//ENROLLMENT
public int getEnrollment() {
return enrollment;
}
public void setEnrollment(int classEnrollment) {
this.enrollment = classEnrollment;
}
//INSTRUCTOR ID
public int getID() {
return ID;
}
public void setID(int instructorID) {
this.ID = instructorID;
}
//TO STRING METHOD
public String toString() {
return ("CRN :" + crn + "\n" +
"Department :" + departmentCode + "\n" +
"Course Number :" + courseNumber + "\n" +
"Instructional mode :" + courseMode + "\n" +
"Meeting days :" + meetingDay + "\n" +
"Meeting times :" + meetingTime + "\n" +
"Capacity :" + capacity + "\n" +
"Enrollment :" + enrollment + "\n" +
"Instructor’s ID :" + ID + "\n");
}
}
Driver
public class ClassDriver {
public static void main(String[] args) {
ClassSection firstInstance = new ClassSection(20008, "CHM", 000, "Online", "N/A", "N/A", 30, 21, 231);
ClassSection secondInstance = new ClassSection();
ClassSection addToList = new ClassSection();
StudentEnrollee studentObj1 = new StudentEnrollee();
StudentEnrollee studentObj2 = new StudentEnrollee();
StudentEnrollee studentObj3 = new StudentEnrollee();
studentObj1.setGrade(5);
studentObj1.setID(230);
studentObj2.setGrade(76);
studentObj2.setID(45);
studentObj3.setGrade(2);
studentObj3.setID(34);
addToList.addStudent(studentObj1);
addToList.addStudent(studentObj2);
addToList.addStudent(studentObj3);
addToList.deletePerson("45");
addToList.displayListV1();
System.out.println(firstInstance.toString());
System.out.println(secondInstance.toString());
}
}
I think it should be:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
You are trying to use a method from subclass in superclass, so you got the error that this method is not defined. You can use all method of superclass in subclasses, but it doesn't work another way.
The getStudentID() method is declared in class StudentEnrollee. In the code below, personObject, which is defined as a ClassSection object, does not have access to it.
public ClassSection locatePerson(String getStudentID) {
for (ClassSection personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}
The solution can vary based on your program logic, but the straightforward way is to replace ClassSection with StudentEnrollee:
public StudentEnrollee locatePerson(String getStudentID) {
for (StudentEnrollee personObject: studentList) {
if (personObject.getStudentID().equals(getStudentID)) {
return personObject;
}
}
return null;
}

How to print out the contents of a HashMap in a certain format?

I'm not entirely sure how I would do this, here is my code:
public class PizzaMenu
{
static Map<String,Pizza> namedPizzas= new HashMap<String,Pizza>();
public static void main(String[] args)
{
}
public static void addItem(String name, Pizza pizza)
{
namedPizzas.put(name, pizza);
}
public String printMenu()
{
/*
String menuString="";
for (Every menu item)
{
//Add name of menu item to menuString with carriage return
//Add details of menu item (pizza.getInfo();) to menuString
}
*/
//return menuString
}
}
I would then call System.out.println(PizzaMenu.printMenu()) in another class. The sort of format I'm hoping to achieve is as follows:
/*
* PizzaName
* Details
*
* Next PizzaName in menu
* Details
*
* Next PizzaName in menu
* Details
*
*
*
*/
Am I maybe using the wrong data structure for this type of operation or is there a way of achieving this?
Here is the structure of the Pizza class (apologies for poor formatting):
public class Pizza
{
private double cost;
private Boolean veg;
private PizzaBase base;
private List<PizzaTopping> toppings = new ArrayList<PizzaTopping>();
public Pizza(PizzaBase base, PizzaTopping topping) //Constructor for pizza with 1 topping
{
setBase (base);
toppings.add(topping);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2) //Constructor for pizza with 2 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
}
public Pizza(PizzaBase base, PizzaTopping topping, PizzaTopping topping2, PizzaTopping topping3) //Constructor for pizza with 3 toppings
{
setBase (base);
toppings.add(topping);
toppings.add(topping2);
toppings.add(topping3);
}
public double getCost()
{
return cost;
}
public void setCost(double cost)
{
this.cost = cost;
}
public PizzaBase getBase()
{
return base;
}
public void setBase(PizzaBase base)
{
this.base = base;
}
public List<PizzaTopping> getToppings()
{
return this.toppings;
}
public String getToppingsInfo()
{
String toppingInfo = "\n";
PizzaTopping t;
for (int i = 0; i<getToppings().size();i++)
{
t = toppings.get(i);
toppingInfo=toppingInfo+t.getInfo();
}
return toppingInfo;
}
public Boolean getVeg()
{
return veg;
}
public void setVeg(Boolean veg)
{
this.veg = veg;
}
public double calculateCost()
{
PizzaTopping p;
//Loop through all ingredients and add their costs to total cost
for (int i = 0; i<toppings.size();i++)
{
p = toppings.get(i);
cost+=p.getCost();
}
cost+=base.getCost(); //Add pizza base cost to total cost
return cost;
}
//Check if pizza is vegetarian depending upon its ingredients
public Boolean isVeg()
{
Boolean toppingCheck =true;
Boolean baseCheck = true;
PizzaTopping t; //Temporary value used to stored toppings being compared in for loop
//Check each topping and check if it's suitable for vegetarians
for (int i =0; i<toppings.size();i++)
{
while (toppingCheck == true)
{
t = toppings.get(i);
if (t.getVeg()==false)
{
toppingCheck = false;
}
}
}
//Check base to see if it's suitable for vegetarians
if (getBase().getVeg()==false)
{
baseCheck = false;
}
//Return value depending on if all ingredients are suitable for vegetarians
if (toppingCheck == true && baseCheck == true)
{
return true;
}
else return false;
}
public String getInfo()
{
String vegInfo;
if (this.isVeg()==true)
{
vegInfo = "Yes";
}
else vegInfo ="No";
return String.format("Toppings:%s\n"+"Base:\n%s"+"\nTotal Cost:\t£%.2f"+"\nSuitable for vegetarians: %s", getToppingsInfo(), getBase().getInfo(), calculateCost(), vegInfo);
//Return list of toppings, Total Price, vegetarian
}
}
Try this:
String menuString="";
for (Map.Entry<String, Pizza> pizzaItem : namedPizzas.entrySet()) {
menuString += pizzaItem.getKey() + "\n";
menuString += "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}
public String printMenu()
{
String s ="";
for (String key: namedPizzas.keySet()){
s+= pizzaItem.getKey() + "\n";
s+= "\t" + pizzaItem.getValue().getInfo() + "\n\n";
}
return menuString
}
To address your question directly:
You need a set of keys. With a set of keys you can also get values. HashMap#keySet should work for this. You can loop through a set using a for each loop.
Then as you said, you need to build your string and return. Putting it together gives you:
public String printMenu()
{
String menuString = "";
for(String key : namedPizzas.keySet())
{
menuString += key + "\n" +
"\t" + namedPizzas.get(key).getInfo() + "\n\n";
}
return menuString;
}
I would also like to suggest a design improvement. You should be overriding the Object#toString method for things like this. The toString method will get automatically called when you try to print the object. This allows you to do: System.out.println(myPizzaMenu); instead of System.out.println(myPizzaMenu.printMenu());
The name printMenu is also misleading, so for that reason it's also bad.
Unfortunately, after switching the map to a list, it still didn't work. An hour later I found the bug causing it all! Thanks for everyone's answers, I will keep these methods in mind when I need to use maps again.
EDIT: Here is the new class structure for reference:
public class PizzaMenu
{
static List<Pizza> namedPizzas = new ArrayList<Pizza>();
public static void main(String[] args)
{
}
public static void addItem(String name, Pizza pizza)
{
pizza.setName(name.toLowerCase());
namedPizzas.add(pizza);
}
public static String printMenu()
{
String menuString="";
Pizza p;
//Collect all pizzas and add their information to string
for (int i =0; i<namedPizzas.size(); i++)
{
p = namedPizzas.get(i);
menuString+=p.getName().toUpperCase()+"\n"+p.getInfo()+"\n\n";
p.resetCost();
}
return menuString;
}
}

Categories

Resources