gpt4 book ai didi

java - 如何创建从商店提款和送货到商店的方法

转载 作者:行者123 更新时间:2023-12-01 14:13:39 25 4
gpt4 key购买 nike

我正在自学java,我想获得关于我自己正在做的锻炼的帮助。该类称为 Product,用于表示小公司销售的产品。

应该可以存储有关每个产品的以下信息。该类应具有以下方法:

  • 构造函数
  • 返回商店中商品单位的方法
  • 向商店送货的方法(增加该产品的数量)
  • 从商店退出的方法(减少该产品的数量)

请注意,如果其中一种方法更改了订单点下方的存储项目,则应打印一条消息。元素数量也不应该为负数。

我的方法有问题。请查看我的代码并给我一些提示。我将感谢所有的回应。谢谢。

这是我的程序:

  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 --;
}
}

最佳答案

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;
}
}

关于java - 如何创建从商店提款和送货到商店的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18298402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com