我的老师要求我们创建一个名为Pizza的课程,用于存储有关单个披萨的信息,该披萨应包含:
存储披萨大小(小,中或大),奶酪,意大利辣香肠和火腿配料数量的私有实例变量。
设置所有实例变量的构造函数。
获取和设置实例变量的公共方法。
一个公共方法名称calcCost(),它返回一个双倍,即披萨的成本。
比萨饼成本由大小决定。小=每顶10美元+ 2美元。中等=每顶12美元+ 2美元。大=每顶14美元+ 2美元。
这是我的班级:
public class Pizza
{
private String pizzaSize;
private int numOfCheese;
private int numOfPepperoni;
private int numOfHam;
public Pizza (String a, int b, int c, int d)
{
a = pizzaSize;
b = numOfCheese;
c = numOfPepperoni;
d = numOfHam;
}
public String getSize()
{return pizzaSize;}
public int getCheese()
{return numOfCheese;}
public int getPepperoni()
{return numOfPepperoni;}
public int getHam()
{return numOfHam;}
public String getDescription()
{
return ("Size: " + pizzaSize + "," + "\t" + "Cheese Toppings: " + numOfCheese +
"\t" + "Pepperoni Toppings: " + numOfPepperoni + "\t" + "Ham Toppings: " +
numOfHam + "\t");
}
public double calcCost()
{
double cost = 0.0;
int numOfToppings;
int costOfToppings;
if (pizzaSize.equals("Small"))
{cost = 10.0;}
else if (pizzaSize.equals("Medium"))
{cost = 12.0;}
else if (pizzaSize.equals("Large"))
{cost = 14.0;}
numOfToppings = ( (numOfCheese + numOfPepperoni) + numOfHam);
costOfToppings = (numOfToppings * 2);
cost += numOfToppings;
return cost;
}
}
这是随附的演示驱动程序:
public class Question11
{
public static void main(String[] args)
{
// Create a few sample pizzas and output their prices
Pizza supreme = new Pizza ("Large",1,2,1);
Pizza cheese = new Pizza ("Medium",2,0,0);
Pizza pepperoni = new Pizza ("Small",0,0,2);
System.out.printf( "%-75sCost: $%5.2f %n", supreme.getDescription(), supreme.calcCost() );
System.out.printf( "%-75sCost: $%5.2f %n", cheese.getDescription(), cheese.calcCost() );
System.out.printf( "%-75sCost: $%5.2f %n", pepperoni.getDescription(), pepperoni.calcCost() );
}
} // Question 11
java.lang.NullPointerException:null错误出现在size.equals部分和supreme.calcCost()上。任何帮助表示赞赏,是的,我在本网站上阅读了其他java.lang.NullPointerException论坛/问题,我仍感到困惑。
答案 0 :(得分:2)
public Pizza (String a, int b, int c, int d) {
pizzaSize = a; // assigns a value to pizzaSize
numOfCheese = b;
numOfPepperoni = c;
numOfHam = d;
}
更改您的Pizza
构造函数。
答案 1 :(得分:1)
你的构造函数倒退,你从方法而不是类字段中分配变量:
public Pizza (String a, int b, int c, int d)
{
a = pizzaSize;
b = numOfCheese;
c = numOfPepperoni;
d = numOfHam;
}
应该是:
public Pizza (String a, int b, int c, int d)
{
pizzaSize = a;
numOfCheese = b;
numOfPepperoni = c;
numOfHam = d;
}
我还建议给它提供比a,b,c,d更有意义的名字