【java】Mall purchase transaction record program design

[Task introduction]

1.Task description

There are many kinds of goods in the mall warehouse. Every time the goods are purchased, a purchase record needs to be generated and saved to the file. This
case requires writing a program to record shopping mall purchase transactions, and using byte streams to record the shopping mall purchase information in a local
CSV file. The specific requirements of the program are as follows.

After the program is started, it first prints all product information existing in the inventory.

When purchasing goods, the user enters the product number, and the program queries the corresponding product information based on the number and prints the product
information. After the user enters the purchased quantity, the current warehousing information is saved to a local CSV file, and the
inventory quantity of the product in the program is updated (new quantity = old quantity + purchased quantity).

In the CSV file saved in this project, the first row is the title row. Each record contains product number, product name,
purchase quantity, unit price, total price, and contact fields. The fields are directly separated by English commas ",".

Records of multiple daily purchases are saved in the same file. The naming format of the file name is "Purchase Record Table"

  • Today's date + ".csv", such as "Purchase Record Table 20200430.csv". When saving a file, you need to determine the local

Whether the file for the current day already exists, if it exists, append the data; if it does not exist, create a new file first.

【mission target】

 Learn to analyze the implementation ideas of the "Mall Purchase Transaction Record" program.

 Independently complete the source code writing, compilation and operation of "mall purchase transaction records" based on ideas.

 Master the File class and byte stream methods for operating local files.

 Master the use of ArrayList, Date, and StringBuffer, as well as exception handling.

 Understand the CSV file format.

[Implementation ideas]

1. In order to facilitate the storage of product-related information, the product information can be encapsulated into an entity class Good.

 The attributes of the product category are:

 int id; // number

 String name; // name

 double price; // unit price

 int amount; // quantity

 double totalPrice; // total price

 String people; //Contact person

 The program needs to print product-related information, so it needs to rewrite the toString() method so that it can return
a string in the specified format. To observe the printing results, analyze the format of the string yourself.

2. In order to demonstrate the purchase of goods in the mall, we need to encapsulate the mall into a Mall class.

 The mall warehouse has a variety of products. Define an ArrayList collection (static member) in the Mall class to simulate
the mall warehouse. Add product objects with specific information to the collection so that the warehouse has products.

 The methods of Mall class are:

 Main method main

 Inventory product initialization method: void initStock()

 Method to display inventory product information: void showStock()

 Product storage operation method: void intoStock()

 Method to find product information based on product number: Good getGoodById(int goodId)

Among these methods, the product storage method intoStock() is the core and most complex part. The process is: obtain
the product number and purchase quantity entered by the user. If the product number is correct and the purchase quantity is normal, the product is successfully
purchased information of this product is saved into a csv file, and the inventory quantity is also required. Increase.
The product number can be obtained through the nextInt() method of the Scanner class, and the information of this product can be queried in the inventory based on this number
. If the product information is found, obtain the quantity of the purchased goods and create an object
good representing the purchased goods. Note that the quantity of this object is the purchased quantity and the total price is the total purchase price.
Finally, save the purchase object information to the file. File operations are more complex and independent. You can design a file operation tool class FileUtil separately , and define a method void saveGood(Good good)
in this class to save the purchase data .

3. The file operation tool class FileUtil has only one static method void saveGood (Good good), which
writes the information of the sales product object good to the csv file.

First, you need to piece together the csv file name (such as "Purchase Record Table 20211111.csv"), and then determine whether
this file already exists locally. This can be determined through the member method isExist() of the File class object. If this file already exists, then the sales information will be added to the end of the file through the output flow. If it does not exist, it means that the sales information of the day
has not been generated before , and this file needs to be created.

The process of data saving is: Good Object Properties→StringBuffer→String→byte[]→Output Stream→File

[Implementation code]

(1) Encapsulate product information into an entity class Good.

(2) Define the Mall class to encapsulate the mall to implement warehousing and display of product information.

(3) Define the tool class FileUtil to save purchase information

package cn.edu.gpnu.bank.cn.edu.gpnu.exp11;

public class Good {
    
    
    int id;
    String name;
    double price;
    int amount;
    double totalPrice;
    String people;

    public Good(int id, String name, String people,double price, int amount) {
    
    
        this.id = id;
        this.name = name;
        this.price = price;
        this.amount = amount;
        this.people = people;
        this.totalPrice=price*amount;
    }

    public int getId() {
    
    
        return id;
    }

    public void setId(int id) {
    
    
        this.id = id;
    }

    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public double getPrice() {
    
    
        return price;
    }

    public void setPrice(double price) {
    
    
        this.price = price;
    }

    public int getAmount() {
    
    
        return amount;
    }

    public void setAmount(int amount) {
    
    
        this.amount = amount;
    }

    public double getTotalPrice() {
    
    
        return totalPrice;
    }

    public void setTotalPrice(double totalPrice) {
    
    
        this.totalPrice = totalPrice;
    }

    public String getPeople() {
    
    
        return people;
    }

    public void setPeople(String people) {
    
    
        this.people = people;
    }

    public String toString() {
    
    
        return "进货商品编号:" + getId() + ", 商品名称" + getName() + ", 联系人:" + getPeople() + ", 单价" + getPrice() + ", 库存数量:" + getAmount() +  "}";
    }
}

package cn.edu.gpnu.bank.cn.edu.gpnu.exp11;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;
public class Mall {
    
    
    //创建商品库存列表
    static ArrayList<Good> stock = new ArrayList<>();

    public static void main(String[] args) {
    
    
        initStock(); //库存商品初始化
        showStock(); //显示库存信息
        intoStock(); //商品入库操作
    }
    /**
     * 库存商品信息初始化
     */
    private static void initStock() {
    
    
        stock.add(new Good(1001, "百事可乐", "张三", 4.5, 100));
        stock.add(new Good(1002, "可口可乐", "李四", 4.0, 100));
        stock.add(new Good(1003, "百事雪碧", "张三", 3.8, 100));
//补充若干行代码
    }

    /**
     * 打印库存的商品信息
     */
    private static void showStock() {
    
    
        System.out.println("库存商品信息如下:");
        Iterator<Good> it = stock.iterator();
        while (it.hasNext()) {
    
    
            Good good = it.next();
            System.out.println(good.toString());
        }
// 补充若干行代码
    }

    /**
     * 商品入库操作
     */
    private static void intoStock() {
    
    
        while (true) {
    
    
            int goodId;
            Scanner scanner = new Scanner(System.in);
            System.out.println("商品入库,请输入商品编号:");
            goodId = scanner.nextInt();
//补充若干行代码
            Good stockGood = getGoodById(goodId);

            if (stockGood != null) {
    
     // 判断是否存在此商品
                int orderAmount;
                System.out.println("请输入进货数量:");
                orderAmount = scanner.nextInt();
//补充若干行代码
// 将入库商品信息封装成 Good 类对象 addGood
                Good addGood = new Good(stockGood.getId(), stockGood.getName(), stockGood.getPeople(), stockGood.getPrice(),orderAmount);
                FileUtil.saveGood(addGood);// 将本条数据保存至本地文件
// 更新库存中该商品数量=原数量+进货数量
                stockGood.setAmount(stockGood.getAmount()+orderAmount);
                stockGood.setTotalPrice(stockGood.getAmount()* stockGood.getPrice());
// 补充代码
// 显示库存信息
                System.out.println("------该商品当前库存信息------");
                showStock();
            } else {
    
    
                System.out.println("商品编号输入错误!");
            }
        }
    }

    /**
     * 根据输入的商品编号查找商品信息
     * 循环遍历库存中商品信息,找到商品编号相等的取出该对象
     */
    private static Good getGoodById(int goodId) {
    
    
        Iterator<Good> it = stock.iterator();
        while (it.hasNext()) {
    
    
            Good good = it.next();
            if(good.getId()==goodId){
    
    
                return good;
            }
        }// 补充若干行代码
        return null;
    }
}

package cn.edu.gpnu.bank.cn.edu.gpnu.exp11;
import java.io.*;
import java.text.*;
import java.text.SimpleDateFormat;
import java.util.Date;

public class FileUtil {
    
    
    /**
     * 保存商品信息
     */
    public static void saveGood(Good good) {
    
    
        BufferedOutputStream bos = null; // 带缓冲的字节输出流
        StringBuffer strBuff = new StringBuffer(); // 拼接输出的内容
        Date date = new Date(); //获取当前时间
        DateFormat dateFormat = new SimpleDateFormat("20211115"); //定义日期格式
        String dateStr = dateFormat.format(date); //将日期转换为格式化字符串
        String fileName = "d:\\进货记录表" + dateStr + ".csv"; // 保存的文件名
        try {
    
    
//判断本地是否存在此文件
            File file = new File(fileName);
            if (!file.exists()) {
    
     //不存在文件,采取新建新文件方式
                file.createNewFile();
                bos = new BufferedOutputStream(new FileOutputStream(fileName));
                System.out.println("文件 " + fileName + " 不存在,已新建文件。");
// 将首行标题进行拼接
                String[] fields = {
    
    "商品编号", "商品名称", "购买数量", "单价", "总价", "联系人"}; // 创建表头
                for (String s : fields) {
    
    
                    strBuff.append(s); //追加字段标题
                    strBuff.append(","); //追加字段分隔符
                }
                strBuff.append("\r\n"); //追加换行符
            } else {
    
     //存在文件,采取修改文件方式
                bos = new BufferedOutputStream(new FileOutputStream(fileName,
                        true));//若文件存在,则追加
                System.out.println("文件 " + fileName + " 已存在,将入库记录附加到文件后面。 ");
            }
// 开始追加商品记录
            strBuff.append(good.getId()).append(",");//先追加 id,再继续追加“,”分隔符
            strBuff.append(good.getName()).append(",");
            strBuff.append(good.getAmount()).append(",");
            strBuff.append(good.getPrice()).append(",");
            strBuff.append(good.getTotalPrice()).append(",");
            strBuff.append(good.getPeople()).append(",");
//补充若干行代码
            strBuff.append("\r\n"); //追加换行符
            String str = strBuff.toString();//将 StringBuffer 对象转换为字符串
            byte[] bytes = str.getBytes("GBK");//以 GBK 字符编码方式将字符串

            bos.write(bytes);
//补充代码,将 bytes 数组的全部内容保存到 bos 流。
            System.out.println("成功保存入库信息。");
        } catch (Exception e) {
    
     //捕获各种异常
            e.printStackTrace();
            System.out.println("保存入库信息失败。");
        } finally {
    
    
            try {
    
    
                if (bos != null)
                    bos.close();
            } catch (Exception e2) {
    
    
                e2.printStackTrace();
            }
//补充代码,安全地关闭 bos 流。
        }
    }
}

【operation result】
Insert image description here

Guess you like

Origin blog.csdn.net/m0_52703008/article/details/126209311