我一直在研究Java程序,学习如何使用和创建构造函数。由于某种原因,我不断收到错误,通知我在实例化对象时我的程序找不到符号。
下面是资源类:
public class Pizza
{
private int size;
private String topping;
private double cost;
public Pizza()
{
size = 10;
topping = "cheese";
cost = 9.00;
}
public Pizza(int s, String t, double c)
{
s = size;
t = topping;
c = cost;
}
public int getSize() {
return size;
}
public void setSize(int s) {
s = size;
}
public String getTopping(){
return topping;
}
public void setTopping(String t){
topping = t;
}
public void setCost(double c) {
cost = c;
}
public double getCost(double c){
return cost;
}
public String toString()
{
return String.format("%d inch %s pizza will cost $%,.2fn", size, topping, cost);
}
}
下面是驱动程序类:
public class PizzaTest
{
public static void main(String[] args)
{
Pizza orderTwo = new Pizza();
System.out.printf("%-25s %s", "Pizza #1", orderTwo);
}
}
我一直在仔细检查代码,但我似乎找不到任何语法错误。任何建议不胜感激。 编译器错误:
PizzaTest.java:6: error: cannot find symbol Pizza orderTwo = new Pizza();
^ symbol: class Pizza location: class PizzaTest
PizzaTest.java:6: error: cannot find symbol Pizza orderTwo = new Pizza();
^ symbol: class Pizza location: class PizzaTest
2 errors
您很可能需要从 PizzaTest 类导入对 Pizza 类的引用。
import <packagename>.Pizza;
显然Pizza
与PizzaTest
位于不同的包中,并且您尚未将适用的import
语句添加到PizzaTest
中。
这是错误所在
public Pizza(int s, String t, double c)
{
s = size;
t = topping;
c = cost;
}
它应该是相反的方式
public Pizza(int s, String t, double c)
{
sise = s;
topping = t;
cost = c;
}
同样在 setSize() 函数中,您也可以以相反的方式使用它
此方法中不应存在参数,请删除double c
public double getCost(double c){
return cost;
}