文件小练习(简易商品系统)

学习目标:

文件小练习(简易商品系统)

学习内容:

商品实体类

public class Product {
	private String pId;
	private String pName;
	private float price;
	public Product() {
	}
	public Product(String pId, String pName, float price) {
		this.pId = pId;
		this.pName = pName;
		this.price = price;
	}
	public String getpId() {
		return pId;
	}
	public void setpId(String pId) {
		this.pId = pId;
	}
	public String getpName() {
		return pName;
	}
	public void setpName(String pName) {
		this.pName = pName;
	}
	public float getPrice() {
		return price;
	}
	public void setPrice(float price) {
		this.price = price;
	}
	@Override
	public String toString() {
		return "[pId=" + pId + ", pName=" + pName + ", price=" + price + "]";
	}
}

主菜单:

public class Menu {
	public static void main(String[] args) throws Exception {
		boolean flag = true;
		Scanner sc = new Scanner(System.in);
		ProductDao dao = new ProductDaoImpl();
		while(flag) {
			System.out.println("1.添加商品  2.查看商品   3.退出");
			String line = sc.nextLine();
			switch(line) {
			case "1":
				System.out.println("请输入商品信息,例如  p1,核桃,4.5");
				String nextLine = sc.nextLine();
				dao.addProduct(nextLine);
				break;
			case "2":
				ArrayList<Product> pdts = dao.getAllProducts();
				for(Product p:pdts) {
					System.out.println(p);
				}
				break;
			case "3":
				flag = false;
				break;
			default:
				System.out.println("您的输入有误,请重新输入!");
				break;
			}		
		}
	}
}

ProductDao接口:

public interface ProductDao {
	public void addProduct(String line) throws Exception;
	
	public ArrayList<Product> getAllProducts() throws Exception;
	
}

ProductDao实现类:

public class ProductDaoImpl implements ProductDao{

	@Override
	public void addProduct(String line) throws Exception{
		BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/a.txt",true),"utf-8"));
		bw.write(line+"\r\n");
		bw.close();
	}
	@Override
	public ArrayList<Product> getAllProducts()  throws Exception{
		ArrayList<Product> pList=new ArrayList<>();
		BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream("d:/a.txt"),"utf-8"));
		String line="";
		while((line=br.readLine())!=null){
			String[] split=line.split(",");
			Product p=new Product(split[0],split[1],Float.parseFloat(split[2]));
			pList.add(p);
		}
		br.close();
		return pList;
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值