50,523
社区成员
发帖
与我相关
我的任务
分享
import java.util.*;
public class Test {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Customer cus = new Customer(2000);
Cashier cas = new Cashier();
cus.getCar().add(new Article("西瓜", (float) 2.5, 8));
cus.getCar().add(new Article("牛奶", (float) 32.5, 2));
cus.getCar().add(new Article("菠萝", (float) 7.5, 2));
cus.getCar().add(new Article("面包", (float) 1.5, 2));
cas.print(cus);
}
}
class Article {
private String name;// 商品名称
private float price;// 商品单价
private int counts;// 购买数量
public Article(String name, float price, int counts) {
this.name = name;
this.price = price;
this.counts = counts;
}
public int getCounts() {
return counts;
}
public void setCounts(int counts) {
this.counts = counts;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}
class ShoppingCar {
public List<Article> car;
public ShoppingCar() {
car = new ArrayList<Article>();
}
/**
* 往购物车放商品
*
* @param article商品
*/
public void add(Article article) {
this.car.add(article);
}
/**
* 从购物车删除商品
*
* @param article商品
*/
public void remove(Article article) {
this.car.remove(article);
}
/**
* 算出购物车商品总价
*
* @return商品总价格
*/
public float total() {
float total = 0;
for (int i = 0; i < car.size(); i++) {
Article temp = car.get(i);
total += temp.getPrice() * temp.getCounts();
}
return total;
}
}
class Customer {
private float money;// 顾客带的总共的钱
private ShoppingCar sc;// 顾客的购物车
public float getMoney() {
return money;
}
public void setMoney(float money) {
this.money = money;
}
public Customer(float money) {
this.money = money;
sc = new ShoppingCar();
}
/**
* 往这个顾客的购物车中添加商品
*
* @param article
*/
public void add(Article article) {
sc.car.add(article);
}
/**
* 往这个顾客的购物车里删除商品
*
* @param article
*/
public void remove(Article article) {
sc.car.remove(article);
}
public List<Article> getCar() {
return sc.car;
}
public ShoppingCar getSc() {
return sc;
}
}
class Cashier {
/**
* 打印收银凭条
*
* @param cs顾客
*/
public void print(Customer cs) {
System.out.println("打印凭条:");
System.out.println("商品名称" + " " + "商品价格" + " " + "商品数量" + " ");
for (int i = 0; i < cs.getCar().size(); i++) {
Article temp = cs.getCar().get(i);
System.out.println(temp.getName() + " " + temp.getPrice() + " " + temp.getCounts());
}
if (cs.getMoney() - cs.getSc().total() > 0) {
System.out.println("应付:" + cs.getSc().total());
System.out.println("实付:" + cs.getMoney());
System.out.println("找零:" + (cs.getMoney() - cs.getSc().total()));
} else {
System.out.println("您的钱不够!");
}
}
}
我给你写了一个,不知道你看不看得懂,拿去可以直接运行