【Java】购物超市
小明去超市买东西,所有买到的东西都放在了购物车之中,最后到收银台一起结账。
package chapter6;
public class Job6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ShoppingCart ps = new ShoppingCart(2);
ps.add(new Phone("iphone5",1,1000));
ps.add(new Computer("huashuo",2,2000));
ps.del("huashuo");
ps.printCart();
System.out.println(Shop.paymen(ps));
}
public static Commodity[] delete(int i, Commodity[] c)
{
Commodity[] cnew = new Commodity[c.length-1];
for(int j=0;j<c.length-1;j++)
{
if(j<i)
{
cnew[j] = c[j];
}
else
{
cnew[j] = c[j+1];
}
}
return cnew;
}
}
interface Commodity
{
public String getName();
public int getAmount();
public double getPrice();
}
class Phone implements Commodity
{
private String name;
private int amount;
private double price;
public Phone(String name, int amount, double price) {
super();
this.name = name;
this.amount = amount;
this.price = price;
}
public String getName() {
return name;
}
public int getAmount() {
return amount;
}
public double getPrice() {
return price;
}
}
class Computer implements Commodity
{
private String name;
private int amount;
private double price;
public Computer(String name, int amount, double price) {
super();
this.name = name;
this.amount = amount;
this.price = price;
}
public String getName() {
return name;
}
public int getAmount() {
return amount;
}
public double getPrice() {
return price;
}
}
class ShoppingCart
{
private Commodity[] goods;
private int foot;
public ShoppingCart(int len)
{
if(len>0)
this.goods = new Commodity[len];
else
this.goods = new Commodity[1];
}
public boolean add(Commodity commodity)
{
if(this.foot<this.goods.length)
{
this.goods[this.foot] = commodity;
this.foot++;
return true;
}
else
{
return false;
}
}
public boolean del(String name)
{
int t = 0;
Commodity[] goodsnew = null;
for(int i = 0;i<this.goods.length;i++)
{
if(this.goods[i]!=null)
{
if(this.goods[i].getName().indexOf(name)!=-1)
{
goodsnew = Job6.delete(i, this.goods);
t = 1;
}
}
}
if(t==1)
{
this.goods = goodsnew;
this.foot--;
return true;
}
else
return false;
}
public void printCart()
{
for(int i=0;i<this.goods.length;i++)
{
if(this.goods[i]!=null)
System.out.println(goods[i].getName()+','+goods[i].getAmount()+','+goods[i].getPrice());
}
}
public Commodity[] getGoods() {
return goods;
}
public int getFoot() {
return foot;
}
}
class Shop
{
public static double paymen(ShoppingCart sc)
{
double sum = 0;
for(int i=0;i<sc.getGoods().length;i++)
{
sum += sc.getGoods()[i].getPrice() * sc.getGoods()[i].getAmount();
}
return sum;
}
}
请你务必,一而再,再而三,三而不竭,千次万次,毫不犹豫地救自己于这世间水火。
笔者将不定期更新【考研或就业】的专业相关知识以及自身理解,希望大家能【关注】我。
如果觉得对您有用,请点击左下角的【点赞】按钮,给我一些鼓励,谢谢!
如果有更好的理解或建议,请在【评论】中写出,我会及时修改,谢谢啦!
笔者将不定期更新【考研或就业】的专业相关知识以及自身理解,希望大家能【关注】我。
如果觉得对您有用,请点击左下角的【点赞】按钮,给我一些鼓励,谢谢!
如果有更好的理解或建议,请在【评论】中写出,我会及时修改,谢谢啦!
本文来自博客园,作者:Nemo&
转载请注明原文链接:https://www.cnblogs.com/blknemo/p/10020201.html
顶
关注
评论
收藏