我自己在学习java,我想获得自己的锻炼方面的帮助。 该类称为产品,用于表示小公司销售的产品。
应该可以存储有关每种产品的以下信息。 该类应具有以下方法:
请注意,如果其中一种方法更改订单点下方的存储项目,则应打印一条消息。也应该不可能有一定数量的项目。
我遇到方法问题。请看一下我的代码并给我一些提示。我会感激所有的回应。 谢谢。
这是我的计划:
public class Product {
private int productNumber;
private String productName;
private float price;
private int orderPoint;
private int unitsInStore;
private String proDescription;
public Product(int num, String name, float price, int order, int units, String description){
this.productNumber = num;
this.productName = name;
this.price = price;
this.orderPoint = order;
this.unitsInStore = units;
this.proDescription = description;
}
public int getProductNumber() {
return productNumber;
}
public void setProductNumber(int productNumber) {
this.productNumber = productNumber;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public int getOrderPoint() {
return orderPoint;
}
public void setOrderPoint(int orderPoint) {
this.orderPoint = orderPoint;
}
// a method returns the units in store
public int getUnitsInStore() {
return unitsInStore;
}
public void setUnitsInStore(int unitsInStore) {
this.unitsInStore = unitsInStore;
}
public String getProDescription() {
return proDescription;
}
public void setProDescription(String proDescription) {
this.proDescription = proDescription;
}
public int deliveranceToStore(int store){
unitsInStore = unitsInStore + store;
return unitsInStore ++ ;
}
public int withdrawal(int store){
unitsInStore = store - unitsInStore;
return unitsInStore --;
}
}
答案 0 :(得分:1)
deliveranceToStore
方法不正确。你为什么要递归地调用这个方法?
该方法可以简单地为:
public int deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
return unitsInStore;
}
如果此次调用无需返回商店中的单位数,则应将返回类型设为void
(即,如果更新计数已足够):
public void deliveranceToStore(int store) {
unitsInStore = unitsInStore + store;
}
对于提款,您需要一个更新unitsInStore
的类似策略:
public void withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
}
}
您还可以使withdrawal
方法返回boolean
,告知撤消操作是否成功。在这种情况下,该方法可能如下所示:
public boolean withdrawal(int units) {
if(unitsInStore - units >= 0) {
unitsInStore = unitsInStore - units;
return true;
} else {
System.out.println("Unable to withdraw. Insufficient units in store.");
return false;
}
}