import java.util.Scanner;
/**
* @ClassName: Que
* @Description: 模拟实现用户购买商品的功能,使用数组模拟商品列表,当购买的商品不存在或者商品库存为0时,抛出自定义异常。
* 用户购买某一个商品时,对异常进行处理,并对库存进行改变。
* @Author: Wanglt
* @CreateDate: 2020年2月29日
*
*/
public class Que {
static int[] goods = { 10, 10, 10, 10, 10, 10 };
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
System.out.println("=============欢迎前来购物=============");
System.out.println("Step1:请输入商品编号");
int index = scanner.nextInt();
System.out.println("Step2:请输入商品数量");
int amount = scanner.nextInt();
try {
sellGoods(index, amount);
} catch (MyException e) {
System.out.println(e.getMessage());
}
System.out.println("=============本次购物结束=============");
}
}
public static void sellGoods(int index, int amount) throws MyException {
if (index < 0 || index >= goods.length) {
throw new MyException("购买的商品不存在");
}
if (goods[index] == 0) {
throw new MyException("商品数量为0,无法购买");
}
if (amount > goods[index]) {
throw new MyException("商品购买数量大于库存,无法购买");
}
System.out.println("继续操作");
goods[index] -= amount;
System.out.println("购物成功!");
}
}
class MyException extends Exception {
public MyException(String msg) {
super(msg);
}
}
自定义异常模拟实现用户购买商品功能
最新推荐文章于 2022-05-28 20:32:24 发布