我们的鬼畜java老师喜欢布置课后作业,然后把代码写在纸上再上交
这次的习题是:
使用面向对象的概念表示出下面的生活场景:
小明去超市买东西,所有买到的东西都放在了购物车之中,最后到收银台一起结账。
先贴下代码,草草写的。
interface Goods{ //使用接口表示商品
public double getPrice();
public String getName();
}
class Toys implements Goods{ //玩具区继承接口Goods
private String name;
private double price;
static String goodName = "玩具";
public double getPrice(){
return this.price;
}
public String getName() {
return this.name;
}
Toys(String name,double price){
this.name = name;
this.price = price;
}
};
class Clothes implements Goods{ //服装区
private String name;
private double price;
static String goodName = "服装";
public double getPrice(){
return this.price;
}
public String getName() {
return this.name;
}
Clothes(String name,double price){
this.name = name;
this.price = price;
}
};
class Drinks implements Goods{ //饮品区
private String name;
private double price;
static String goodName = "饮品";
public double getPrice(){
return this.price;
}
public String getName() {
return this.name;
}
Drinks(String name,double price){
this.name = name;
this.price = price;
}
};
class Foods implements Goods{ //食品区
private String name;
private double price;
static String goodName = "食品";
public double getPrice(){
return this.price;
}
public String getName() {
return this.name;
}
Foods(String name,double price){
this.name = name;
this.price = price;
}
};
class ShopTotal{
private Goods[] Good; //模拟购物车
private int foot; //购买的商品数量
private double total;
static int len = 5;
ShopTotal(){
this.Good = new Goods[len];
}
public void add(Goods good){
if(this.foot >= this.Good.length){ //当商品数大于购物车的容量就要进行扩容
Goods[] goods = new Goods[this.Good.length+len];
System.arraycopy(this.Good, 0, goods, 0, this.Good.length);
this.Good = goods;
}
this.Good[this.foot] = good;
this.foot++;
}
public double totalMoney(){
for(int i = 0;i<this.foot;i++){
total += Good[i].getPrice();
}
return this.total;
}
public int getNumber(){
return this.foot;
}
};
public class ShoppingMall {
public static void main(String args[]){
ShopTotal st = new ShopTotal();
st.add(new Toys("手枪",25.5));
st.add(new Toys("飞机",84.3));
st.add(new Drinks("特伦舒(箱)",73.5));
st.add(new Foods("乐事薯片",8.5));
st.add(new Clothes("牛仔裤",120));
st.add(new Clothes("白T",60));
System.out.println("共购买"+st.getNumber()+"件商品,合计"+String.format("%.2f", st.totalMoney())+"元");
}
}
写得很简单,这次作业学到了动态数组的扩容。