如何在Java代码中为商品添加优惠券抵扣价格功能
Java 优惠券功能实现方案
原有代码存在的问题
- 你设想的
coupon方法直接调用了main方法内的局部变量cookie,实例方法无法直接访问其他方法的局部变量,编译会报错 - 你期望的调用语法
Store coupon = new coupon("freecookies");错误,coupon不是类定义,无法通过new关键字实例化 - 原有设想的优惠券方法中,
System.out.println("Invalid Coupon!")行末尾缺少分号,不符合Java语法规范
基础实现方案
我们可以将优惠券方法调整为静态工具方法,针对你指定的「输入freecookies减饼干价格」的需求,调整后完整代码如下:
public class Store { // 实例属性 String productType; double price; // 构造方法 public Store(String product, double initialPrice) { productType = product; price = initialPrice; } // 价格调整方法 public void modifyPrice(double priceInputed){ double newPrice = price + priceInputed; price = newPrice; } // 优惠券应用方法,传入要优惠的饼干对象和用户输入的优惠码 public static void applyCoupon(Store cookie, String codeEntered){ String validCode = "freecookies"; if (codeEntered.equals(validCode)) { cookie.modifyPrice(-1); System.out.println("优惠券应用成功!"); }else{ System.out.println("Invalid Coupon!"); } } // 主方法 public static void main(String[] args) { Store lemonade = new Store("Lemonade", .75); Store cookie = new Store("Cookie", 1.00); lemonade.modifyPrice(6.5); cookie.modifyPrice(1); // 调用优惠券方法 applyCoupon(cookie, "freecookies"); System.out.println(String.format("%.2f", cookie.price) + "$" + " For a cookie"); System.out.println(String.format("%.2f", lemonade.price) + "$" + " For a lemonade"); } }
执行上述代码后,饼干最终价格会从2.00$降至1.00$,符合你的降价需求。
贴近你期望调用方式的实现
如果你想要使用和你设想的new coupon("freecookies")接近的写法,可以单独定义优惠券类:
// 单独定义的优惠券类 class Coupon { public Coupon(String codeEntered, Store cookie){ String validCode = "freecookies"; if (codeEntered.equals(validCode)) { cookie.modifyPrice(-1); System.out.println("优惠券应用成功!"); }else{ System.out.println("Invalid Coupon!"); } } }
之后在main方法里直接调用new Coupon("freecookies", cookie);即可触发优惠,和你预期的调用逻辑完全匹配。
内容的提问来源于stack exchange,提问作者Yaroslav .O
相关产品推荐
相关产品推荐

