Ok so basically this is my program it's about Students & Student Groups;
Each student has a name, ID and marks/points;
The program is working fine but what's missing is that the SUM function in the class StudentsGroup needs to be static and to take a parameter of the "Group" of which you need the sum of points. My problem is that when I put the function and the ArrayList to static, the function returns both of the groups score combined and I don't know how to make it work
//the program works correctly and returns the correct values about
everything; i only get those errors when i try to change the
sumOfPoints function to static
the two files that i have are:
Group 1:
61662126 Laurel 50
61662213 Mark 35.5
61662345 Yanny 67
61662127 Larry 27
61662125 Kevin 87.5
and Group 2:
61662126 Jason 70
61662213 Josh 25.5
61662345 Bobby 57
61662127 Megan 17
61662125 Drake 86.5
the correct output should be:
Total points of Group1: 267.0
Total points of Group2: 256.0
Comparing Group1 to Group2: 1
but when i put it to static it returns 523 in both which is both of the groups combined and i don't understand what im doing wrong
public interface IFile
{
public void Load();
}
public class Student implements Comparable<Student>
{
private int facnum;
private String name;
private double points;
public Student(int fn, String n, double p)
{
this.facnum = fn;
this.name = n;
this.points = p;
}
public void SetFN(int fn)
{
this.facnum = fn;
}
public void SetName(String n)
{
this.name = n;
}
public void SetPoints(double p)
{
this.points = p;
}
public int GetFN()
{
return this.facnum;
}
public String GetName()
{
return this.name;
}
public double GetPoints()
{
return this.points;
}
public boolean equals(Object s)
{
if (this.GetFN() != ((Student)s).GetFN())
{
return false;
}
return true;
}
public int compareTo(Object s)
{
if(this.GetFN() < ((Student)s).GetFN())
{
return -1;
}
if(this.GetFN() > ((Student)s).GetFN())
{
return 1;
}
return 0;
}
public String toString()
{
return "Faculty Number: " + this.facnum + " Name: " + this.name + " Points: " + this.points + " \n";
}
}
import java.io.*;
import java.util.*;
public class StudentsGroup implements IFile, Comparable<Object>
{
private String groupname;
private List<Student>oStudent = new ArrayList<Student>();
public StudentsGroup(String filename)
{
this.groupname = filename;
Load();
}
public void Load(){
try
{
Scanner sc=new Scanner(new File(this.groupname));
while(sc.hasNextLine())
{
oStudent.add(new Student(sc.nextInt(),sc.next(),
sc.nextDouble()));
}
sc.close();
}
catch(IOException e)
{
System.out.println("Input/Output Error...");
}
}
public void printColl()
{
System.out.println(oStudent.toString());
}
public List<Student> sortedListFN()
{
Collections.sort(oStudent);
return oStudent;
}
public double sumOfPoints()
{
double sum = 0.00;
for(Iterator<Student> it= oStudent.iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints() < ((StudentsGroup) s).sumOfPoints())
{
return -1;
}
if(this.sumOfPoints() > ((StudentsGroup) s).sumOfPoints())
{
return 1;
}
return 0;
}
public static void main(String[] args)
{
StudentsGroup oGroup1 = new StudentsGroup("Group1.txt");
oGroup1.printColl();
System.out.println("Sorted order by FN: " + oGroup1.sortedListFN() + "\n");
StudentsGroup oGroup2 = new StudentsGroup("Group2.txt");
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints() + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints() + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
}
}
edit//the static method that i tried is changing oStudent to static:
private static List<Student>oStudent = new ArrayList<Student>();
obviously changing the sum function to static & editing the compareTo method:
public static double sumOfPoints(Object s)
{
double sum = 0.00;
s = new ArrayList<Student>(oStudent);
for(Iterator<Student> it= ((List<Student>) s).iterator(); it.hasNext();)
{
Student c = it.next();
sum += c.GetPoints();
}
return sum;
}
public int compareTo(Object s)
{
if(this.sumOfPoints(this) < ((StudentsGroup) s).sumOfPoints(s))
{
return -1;
}
if(this.sumOfPoints(this) > ((StudentsGroup) s).sumOfPoints(s))
{
return 1;
}
return 0;
}
and the output:
System.out.println("Total points of Group1: " + oGroup1.sumOfPoints(oGroup1) + "\n");
System.out.println("Total points of Group2: " + oGroup2.sumOfPoints(oGroup2) + "\n");
System.out.println("Comparing Group1 to Group2: " + oGroup1.compareTo(oGroup2));
and the output starts returning 523
Your static method overwrites s with the inner object of that particular instance class:
s = new ArrayList<Student>(oStudent);
I think your mistake is here. This is not how you use a static method of class. The correct way to do it is StudentsGroup.sumOfPoints(yourObjectHere). A static method should not know about any field of a particular instance.
Related
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?
I'm looking for help on an error that I am getting while trying to create this java class. I want to add test scores as well as the average for this student class. I have tried a lot of things and I cant seem to get the error "Variable declaratorid expected after this method" to go away when I reach my setTestScore method shown below (shown with arrows) similarly in my next getTestScore method I have an error "cant invoke getTest() on the primitive type int." (also show with arrows)
public class Student {
private String firstName, lastName;
private Address homeAddress, schoolAddress;
private int TestScore, testScores ;
private int testScore1, testScore2, testScore3;;
public void TestScore(int testScore1, int testScore2, int testScore3)
{
this.testScore1 = testScore1;
this.testScore2 = testScore2;
this.testScore3 = testScore3;
}
public Student(String first, String last, Address home, Address school)
{
this.firstName = first;
this.lastName = last;
this.homeAddress = home;
this.schoolAddress = school;
}
testScores = new TestScore(testScore1, testScore2, testScore3);
public void setTestScore(int testNumber, int TestScore) {
if(testNumber==1) {
testScores.setTest1(>>testScore<<);
}
else if(testNumber==2) {
testScores.setTest2(>>testScore<<);
}
else if(testNumber==3) {
testScores.setTest3(>>testScore<<);
}
}
public void setTest1(int test1) {
this.testScore1 = test1;
}
public void setTest2(int test2) {
this.testScore2 = test2;
}
public void setTest3(int test3) {
this.testScore3 = test3;
}
public int getTestScore(int testNumber) {
if(testNumber==1) {
return >>testScores.getTest1<<();
}
else if(testNumber==2) {
return >>testScores.getTest2<<();
}
else if(testNumber==3) {
return >>testScores.getTest3<<();
}
else {
return 0;
}
}
public int getTest1() {
return testScore1;
}
public int getTest2() {
return testScore2;
}
public int getTest3() {
return testScore3;
}
public double getAverageTestScores() {
double avg;
avg=(testScores.getTest1() + testScores.getTest2() + testScores.getTest3())/3.0;
return avg;
}
public String toString()
{
String result;
result = firstName + " " + lastName + "\n";
result += "Home Address:\n" + homeAddress + "\n";
result += "School Address:\n" + schoolAddress + "\n";
result +="Test Score 1:\n" + testScores.getTest1() + "\n";
result +="Test Score 2:\n" + testScores.getTest2() + "\n";
result +="TestScore 3:\n" + testScores.getTest3() + "\n";
result +="Average test score:\n" + getAverageTestScores() + "\n";
return result;
}
}
remove this statement
testScores = new TestScore(testScore1, testScore2, testScore3);
and where ever you have used
testScores.foo
in your program,replace it with
this.foo
remove this statement
testScores = new TestScore(testScore1, testScore2, testScore3);
and where ever you have used
testScores.foo
in your program,replace it with
this.foo
I've been having some issues with this program. I have to test out using a driver class each method, but I can't seem to understand what I should do when the parameters are strings.
I had an example for int parameters but the example never showed anything on string parameters and how to convert. Using null makes my driver class run but putting an int or string won't.
What can I do to convert this correctly, so it can display whatever I have in the no parameter constructor?
public class StudentListing
{
private String name;
private String number;
public StudentListing(String n, String num)
{
name = n;
number = num;
}
public StudentListing()
{
name = null;
number = null;
}
public String toString()
{
return("Name is " + name +
"\nNumber is " + number + "\n");
}
public void show()
{
System.out.println(toString());
}
public StudentListing Clone()
{
StudentListing clone = new StudentListing (name, number);
return clone;
}
public int compareTo(String targetKey)
{
return (name.compareTo(targetKey));
}
public void input()
{
name = JOptionPane.showInputDialog("Enter a name");
number = JOptionPane.showInputDialog("Enter a number");
}// end of StudentListing
}//end of class
public class StudentListingDriver
{
public static void main(String[] args)
{
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null,null);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.clone();
s1.show();
}
}
You can have default values and make the no-args constructor call the other constructor.
Use Integer.parseInt(); to convert from a String to an Integer.
You also need to check the conversion for exceptions.
Like this:
public class StudentListing {
private String name;
private int number;
public StudentListing(String n, int num) {
name = n;
number = num;
}
public StudentListing() {
this("defaultName", 0);
}
public String toString() {
return ("Name is " + name + "\nNumber is " + number + "\n");
}
public void show() {
System.out.println(toString());
}
public StudentListing Clone() {
StudentListing clone = new StudentListing(name, number);
return clone;
}
public int compareTo(String targetKey) {
return (name.compareTo(targetKey));
}
public void input() {
name = JOptionPane.showInputDialog("Enter a name");
number = Integer
.parseInt(JOptionPane.showInputDialog("Enter a number"));
}
}
The tester:
public class StudentListingDriver {
public static void main(String[] args) {
StudentListing s1 = new StudentListing();
StudentListing s2 = new StudentListing(null, 0);
System.out.println(s1);
s1.input();
StudentListing s3 = s2.Clone();
s1.show();
}
}
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;
}
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;
}
}