编写一个商品类,包括货号,商品名称,单价,库存,商品类别等字段,且要封装属性。编写带参的构造函数和空构造函数。编写一个SHOW()方法显示类的所有属性。编写一个饮料类,继承于商品类,饮料类中多出一个容量属性。继承要求构造函数赋值。主函数中,创立一个长度为10的商品类数组。并创建3个以上的对象填充数组。通过循环调用数组每一个对象的show方法显示商品信息。用户输入商品的货号,查找是否存在该商品,存在则再让用户输入购买数量,并将该商品的库存量减去购买数量,同时显示付款总数,注意库存量不可为负数。如果查不到商品货号也提示输入有误。
using System;
class Commodity
{
private string id; // 货号
private string name; // 商品名称
private double price; // 单价
private int stock; // 库存
private string category; // 商品类别
// 属性的封装
public string Id
{
get { return id; }
set { id = value; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public double Price
{
get { return price; }
set { price = value; }
}
public int Stock
{
get { return stock; }
set { stock = value; }
}
public string Category
{
get { return category; }
set { category = value; }
}
// 带参构造函数
public Commodity(string id, string name, double price, int stock, string category)
{
this.id = id;
this.name = name;
this.price = price;
this.stock = stock;
this.category = category;
}
// 空构造函数
public Commodity()
{
this.id = "";
this.name = "";
this.price = 0;
this.stock = 0;
this.category = "";
}
// 显示所有属性
public void Show()
{
Console.WriteLine("货号:" + id);
Console.WriteLine("商品名称:" + name);
Console.WriteLine("单价:" + price);
Console.WriteLine("库存:" + stock);
Console.WriteLine("商品类别:" + category);
}
}
class Beverage : Commodity
{
private double capacity; // 容量
// 容量属性的封装
public double Capacity
{
get { return capacity; }
set { capacity = value; }
}
// 带参构造函数
public Beverage(string id, string name, double price, int stock, string category, double capacity)
: base(id, name, price, stock, category)
{
this.capacity = capacity;
}
// 空构造函数
public Beverage() : base()
{
this.capacity = 0;
}
// 重写显示方法
public new void Show()
{
base.Show();
Console.WriteLine("容量:" + capacity);
}
}
class Program
{
static void Main(string[] args)
{
Commodity[] commodities = new Commodity[10];
// 创建对象并填充数组
commodities[0] = new Commodity("001", "手机", 999.9, 100, "电子产品");
commodities[1] = new Commodity("002", "电视", 2999.9, 50, "电子产品");
commodities[2] = new Beverage("003", "可乐", 3.5, 200, "饮料", 500);
commodities[3] = new Beverage("004", "矿泉水", 2.0, 500, "饮料", 550);
// ...
// 循环调用显示方法
for (int i = 0; i < commodities.Length; i++)
{
if (commodities[i] != null)
{
Console.WriteLine("第" + (i + 1) + "个商品信息:");
commodities[i].Show();
Console.WriteLine();
}
}
// 查找商品并购买
Console.Write("请输入要购买的商品货号:");
string id = Console.ReadLine();
bool found = false;
for (int i = 0; i < commodities.Length; i++)
{
if (commodities[i] != null && commodities[i].Id == id)
{
found = true;
Console.Write("请输入购买数量:");
int quantity = int.Parse(Console.ReadLine());
if (quantity <= commodities[i].Stock)
{
commodities[i].Stock -= quantity;
Console.WriteLine("购买成功,付款总额为:" + quantity * commodities[i].Price);
}
else
{
Console.WriteLine("库存不足!");
}
break;
}
}
if (!found)
{
Console.WriteLine("输入有误,未找到该商品!");
}
Console.ReadKey();
}
}