我不断得到一个标识符预期错误,它在我的代码末尾显示“public double calcTotal(calcCost){”。请注意,我正在从另一个类调用一个方法。有什么问题?此外,请随时指出您在我的代码中看到的任何其他错误。我很害怕,一旦我解决了这个错误,当我再次尝试编译时会弹出10个以上。谢谢!
public class PizzaOrder {
private String [] m_Pizza; //array for base type Pizza
private int m_numPizzas;
//default constructor
public PizzaOrder() {
m_Pizza = null;//new String[0]
m_numPizzas = 0;
}
//overloaded Pizza
public PizzaOrder(String [] Pizza, int numPizzas) {
m_Pizza = Pizza;
m_numPizzas = numPizzas;
}
//public methods
public void setPizza (String [] Pizza){
m_Pizza = Pizza;
}
public String getPizza () {
return m_Pizza;
}
public void setNumPizzas (int numPizzas) {
m_numPizzas = numPizzas;
}
public int getNumPizzas () {
return numPizzas;
}
public void addPizza(Pizza pizza) {
if (m_Pizza.length() <= m_numPizzas) {
m_Pizza.length() = m_numPizzas;
//m_Pizza[m_numPizzas] = Pizza; //pizza array has same amount of items as numPizzas
m_numPizzas++;
}
else {
System.out.println("Adding an additional pizza was unuccessful.");
}
}
public double calcTotal(calcCost){
double totalCost = 0;
double Cost = calcCost(); //calling calcCost function
for (int i = 0; i < m_Pizza.length(); i++) { //goes through array
calcCost(m_Pizza[i]); //calculates cost for each pizza in array
Cost += totalCost; //adds each cost to total
return totalCost;
}
}
public String toString() {
double total = calcTotal(calcCost); //stores calcTotal function in total variable
System.out.println("You ordered a " + m_Pizza + ". Your total cost is: " + total);
}
}
是的,这个方法似乎有很多问题,我已经添加了评论
public double calcTotal(calcCost){
double totalCost = 0;
double Cost = calcCost(); // is there really a zero parameter method ?
for (int i = 0; i < m_Pizza.length(); i++) {
calcCost(m_Pizza[i]); // this takes a parameter but does not use the return value
Cost += totalCost; // totalCost is always zero, do you mean totalCost += Cost; ?
return totalCost; // you are returning this value with in the for loop
}
// compile error here as it is expecting some value to be returned
}
提示:将返回值移到循环外部
将calCost的价值保存到成本
将Cost的值添加到totalCost
同样,@ markspace提到这个方法的参数有问题,实际上是否需要?
在循环结束后,您应该在方法结束时添加“return”语句。
public double calcTotal(calcCost){
double totalCost = 0;
double Cost = calcCost(); //calling calcCost function
for (int i = 0; i < m_Pizza.length(); i++) { //goes through array
calcCost(m_Pizza[i]); //calculates cost for each pizza in array
Cost += totalCost; //adds each cost to total
}
return totalCost;
}
想想当m_Pizza变量为空时,控件不会进入for循环然后返回什么方法?所以上面是修复。