【发布时间】:2021-07-03 23:26:04
【问题描述】:
我正在尝试编写一个 getter 方法来查找数组中所有元素的总和并返回一个双精度值。问题是我从另一个类传递了一个对象数组,而我根本不知道如何用对象编写一个 sum 数组。
这是我正在尝试创建的方法
private double getTotal() {
double accumulator=0;
for(int i=0;i<items.length;i++) {
accumulator += items[i];
}
return accumulator;
}
这是我正在使用的课程
public class Item {
//class fields
private String name;
private double price;
private int quantity;
//class constructor
/**
* class constructor for Item (takes in 3 arguments and sets them appropriately)
* @param n :name
* @param p :price
* @param q :quantity
*/
public Item(String n, double p, int q) {
name =n;
price =p;
quantity =q;
}
//getters for all fields
/**
* getter method for name field of item class
* @return name
*/
public String getName() {
return name;
}
/**
* getter method for price field of item class
* @return price
*/
public double getPrice() {
return price;
}
/**
* getter method for quantity field of item class
* @return quantity
*/
public int getQuantity() {
return quantity;
}
/**
* getter method that computes sub total and returns it
* @return subTotal
*/
public double getSubTotal() {
double subTotal = price*quantity;
return subTotal;
}
//to String method
/**
* toString method for the item class
*/
public String toString() {
String output= "";
output += String.format("%10.s%5.d%5.2f%5.2f\n",name,quantity, price,subTotal );
return output;
}
}
(是的,我知道 toString 方法中的错误,但这是另一个错误)
在我的作业中,我必须为此使用 getSubTotal() 方法。而且我不能在我的程序中的任何地方将我的任何方法设置为静态的。我希望有人可以帮助我。
【问题讨论】:
-
你的意思可能是:+= items[i].getPrice();
-
我猜你需要
accumulator += items[i].getSubTotal(); -
这似乎可以做到。现在我只需要修复了 toString 错误:D
-
in
toString()remove.s in%10.s和%5.d,像这样:output += String.format("%10s %5d %5.2f %5.2f\n",name,quantity, price,subTotal ); -
subTotal 仍未解析为变量
标签: java arrays object methods