Now, everything in my code works correctly. Everything displays as it should and the cost is calculated correctly. I am just curious as to the point of the accessor methods in this particular class. Perhaps I am missing something and my code is just wrong but it seems that the display() method takes care of 'accessing' the variables.
Pizza Class
public class Pizza {
private String size; // small, medium, large
private int cheese; // number of cheese toppings
private int pepp; // number of pepperoni toppings
private int ham; // number of ham toppings
private double cost;
// constructor
public Pizza() {
size = "";
cheese = 0;
pepp = 0;
ham = 0;
}
// set methods
public void setSize(String s) {
size = s;
}
public void setToppings(int c, int p, int h) {
cheese = c;
pepp = p;
ham = h;
}
// get methods
public String getSize() {
return size;
}
public int getCheese() {
return cheese;
}
public int getPepp() {
return pepp;
}
public int getHam() {
return ham;
}
// cost method
public double calcCost() {
if(size == "small") {
cost = 10 + (2 * cheese) + (2 * pepp) + (2 * ham);
}
else if(size == "medium") {
cost = 12 + (2 * cheese) + (2 * pepp) + (2 * ham);
}
else if(size == "large") {
cost = 14 + (2 * cheese) + (2 * pepp) + (2 * ham);
}
return cost;
}
// print method
public void display() {
System.out.printf("Pizza Size: %s ", size);
System.out.printf("Toppings: %d cheese, %d pepperoni, %d ham ", cheese, pepp, ham);
System.out.printf("Total Cost: $%.2f", cost);
System.out.println();
}
}
and the PizzaDriver class to test it
public class PizzaDriver {
/**
* Tests the methods of the Pizza class
*/
public static void main(String[] args) {
Pizza pizza1 = new Pizza();
Pizza pizza2 = new Pizza();
Pizza pizza3 = new Pizza();
pizza1.setSize("small");
pizza1.setToppings(1, 0, 1);
pizza2.setSize("medium");
pizza2.setToppings(1, 1, 1);
pizza3.setSize("large");
pizza3.setToppings(1, 1, 2);
pizza1.calcCost();
pizza1.display();
System.out.println();
pizza2.calcCost();
pizza2.display();
System.out.println();
pizza3.calcCost();
pizza3.display();
System.out.println();
}
}

New Topic/Question
Reply




MultiQuote




|