我們的鬼畜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())+"元");
}
}
寫得很簡單,這次作業學到了動態數組的擴容。