public static Scanner input;
public static Goods[] goods;//创建一个Goods对象数组
static {
input=new Scanner(System.in);
goods=new Goods[3];//将对象放在数组,并且初始化值
goods[0]=new Goods(1,"苹果",20,2.5);
goods[1]=new Goods(2,"香蕉",12,1.5);
goods[2]=new Goods(3,"橘子",3,3);
}
private static void showinfo(){
for (Goods good : goods) {
System.out.println(good.toString());
}
}
private static void buy() throws NoGoodsException, NotEnoughException {
Goods gname=null;//创建一个对象
System.out.println("请选择要购买的商品名称");
String name=input.next();
for(Goods goods1:goods){
if(goods1==null)break;
if(goods1.getName().equals(name)){
gname=goods1;
}
}
//下面语句要放在循环体外面,用另一个判断继续
if(gname==null) {
throw new NoGoodsException("商品不存在");
}
else System.out.println("商品存在可以买了,您要买几个?");
int num=input.nextInt();
if(gname.getStore()<num){
throw new NotEnoughException("库存不足");
}else{
System.out.println("您需要支付"+(gname.getPrice()*num)+"元购买"+(gname.getName()));
}
gname.setStore(gname.getStore()-num);
showinfo();
}
public static void main(String[] args) {
//模拟实现用户购买商品的功能,
// 当购买的商品不存在或者商品库存为0时,
// 抛出自定义异常。用户购买某一个商品时,
// 对异常进行处理,并对库存进行改变。
try {
buy();
} catch (NoGoodsException e) {
e.printStackTrace();
} catch (NotEnoughException e) {
e.printStackTrace();
}
}
标签:Goods,商品,goods,static,购买,gname,new,模拟
From: https://www.cnblogs.com/Liku-java/p/16823619.html