【发布时间】:2016-03-15 04:21:17
【问题描述】:
我的老师给了我关于这个编码作业的令人困惑的指示。如果你们可以帮助详细说明或给我提示,我会提供我所拥有的。
首先,我必须在该程序中创建 2 个类,它们将与一个大类一起生成一个购物清单,您可以在其中编辑您想要的每件商品的数量。必须记下商品的名称、购买次数以及每件的价格。
我完成了我的第一节课,我将在这个问题的底部发布整个编码和编码规则。
好的,这就是我所拥有的。我会一步一步来。 规则 1:一个字段 private Purchase[] 作为购买数组。 另一个用于跟踪实际购买次数的 int 字段
所以我做了这个:
private int Purchase[];
private int purchaseCount;
规则 2:负值没有意义,所以如果用户提供,只需将它们重置为零
好的,所以在第一个程序中我必须做同样的事情,但我现在很困惑如何去做。
我在修饰符中实现了“重置为零”,但现在我的老师没有要求修饰符。我应该把它们放在哪里?我知道我只需要写一个“如果 blahblahblah
规则 3:Accessor .length() 方法返回您的 int 字段以表示购买次数
public int Purchase(){
return ;
}
我想这就是我所知道的一切。我知道我必须返回一些东西,但不确定如何使用长度。而且我认为有一个参数。
最终规则 4:Purchase 数组的访问器 .get(int),它需要一个参数来索引数组。所以 get(0) 返回数组的第一个元素(一个 Purchase 对象)。
我想我明白这一点,但由于我不知道如何做最后一步,所以我还没有尝试过。 “.get(int)”什么?那么我在其中执行 .get(int) 的访问器?我对访问器了解不多,这就是我需要这个帮助的原因。程序的其余部分对我来说似乎很简单,但是这个最初的东西让我感到困惑。谢谢。
已完成课程的规则:
三个字段,一个 String 代表购买的名称,int 代表购买的单位,double 代表每单位的成本。 • 每个字段的标准访问器和修饰器方法。 • 不允许使用负值,因此在所有情况下都将其更改为零。 • 按顺序初始化这三个字段(String、int、double)的构造函数。 • 构造函数重载,(String, double) 假定 int 数量为零。 • 假定名称为“”且数字为零的默认构造函数,必须调用三参数构造函数。 • getCost 方法,它只是购买的单位数量乘以单位价格。 • toString 方法返回一个带有项目名称的字符串,后跟括号中的单价
完成的程序:
public class Purchase {
private String purchase;
private int unitsPurchased;
private double costPerUnit;
// Accessors
public String purchase() {
return purchase;
}
public int unitsPurchased() {
return unitsPurchased;
}
public double costPerUnit() {
return costPerUnit;
}
// Modifiers
public void setPurchase(String purchase) {
this.purchase = purchase;
}
public void setunitsPurchased(int unitsPurchased) {
if (unitsPurchased < 0) {
unitsPurchased = 0;
}
this.unitsPurchased = unitsPurchased;
}
public void setCostPerUnit(double costPerUnit) {
if (costPerUnit < 0) {
costPerUnit = 0;
}
this.costPerUnit = costPerUnit;
}
//constructors
public Purchase() {
this("", 0, 0);
}
public Purchase(String initialPurchase, double initialCostPerUnit) {
this.purchase = initialPurchase;
this.unitsPurchased = 0;
this.costPerUnit = initialCostPerUnit;
}
public Purchase(String initialPurchase, int initialUnitsPurchased, double initialCostPerUnit) {
this.purchase = initialPurchase;
this.unitsPurchased = initialUnitsPurchased;
this.costPerUnit = initialCostPerUnit;
}
//end of everything I am sure about
//beginning of unsurety
public static double getCost(String purchase, int unitsPurchased, double costPerUnit) {
return unitsPurchased * costPerUnit;
}
public static String toString(String purchase, int unitsPurchased, double costPerUnit){
return purchase + costPerUnit;
}
}
【问题讨论】:
标签: java