【Java】东北大学面向对象实验Gourmet咖啡系统

本文介绍了一个使用Java实现的咖啡馆销售系统实验项目。该系统包括产品目录加载、订单管理及不同格式的销售报告生成等功能。通过命令行界面进行交互,支持从文件中读取商品信息,并能保存销售记录为纯文本、HTML或XML格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

废话不多说,直接上实验代码
运用了接口,JAVA的字符串分段,字符的录入txt

FileCatalogLoader.java

package experiment4;
import experiment1.*;
import experiment2.*;
import experiment3.*;
import java.util.*;
import java.io.*;
import java.lang.*;

public class FileCatalogLoader implements CatalogLoader {
    private Product readProduct(String line) throws DataFormatException {
        StringTokenizer a = new StringTokenizer(line, "_");
        if (a.countTokens() != 4) {
            throw new DataFormatException(line);
        } else {
            try {
                String str1 = a.nextToken();
                return new Product(a.nextToken(), a.nextToken(), Double.parseDouble(a.nextToken()));
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    private Coffee readCoffee(String line) throws DataFormatException {
        StringTokenizer b = new StringTokenizer(line, "_");
        if (b.countTokens() != 10)//分割成多少个字符串
            /**int countTokens():返回nextToken方法被调用的次数。
         boolean hasMoreTokens():返回是否还有分隔符。
        String nextToken():返回从当前位置到下一个分隔符的字符串*/
    {
            throw new DataFormatException(line);
        } else {
            try {
                String str2 = b.nextToken();
                return new Coffee(b.nextToken(), b.nextToken(), Double.parseDouble(b.nextToken()), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken(), b.nextToken());
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    private CoffeeBrewer readCoffeeBrewer(String line) throws DataFormatException {
        StringTokenizer c = new StringTokenizer(line, "_");
        if (c.countTokens() != 7) {
            throw new DataFormatException(line);
        } else {
            try {
                String str3 = c.nextToken();
                return new CoffeeBrewer(c.nextToken(), c.nextToken(), Double.parseDouble(c.nextToken()), c.nextToken(), c.nextToken(), Integer.parseInt(c.nextToken()));
            } catch (NumberFormatException num) {
                throw new DataFormatException(line);
            }
        }
    }

    public Catalog loadCatalog(String filename) throws FileNotFoundException, IOException, DataFormatException {
        Catalog cata = new Catalog();
        FileReader file = new FileReader(filename);//把数据读取到缓冲流,字符操作
        BufferedReader a = new BufferedReader(file);//定义一个操作缓冲流的对象
        String line;
        //startsWith判断XX字符串开头,返回bool
        while ((line=a.readLine()) != null) {
            Object obj;
            if (line.startsWith("Coffee")) {
                obj = this.readCoffee(line);
            } else if (line.startsWith("Brewer")) {
                obj = this.readCoffeeBrewer(line);
            } else {
                if(!line.startsWith("Product")) {
                    throw new DataFormatException(line);
                }
                    obj = this.readProduct(line);
                }
                cata.addProduct((Product) obj);//强制转换
            }
            a.close();//缓冲流关闭
        file.close();//文件关闭
        return cata;
        }

    }



GourmetCoffee.java

package experiment4;

import java.io.*;
import java.util.*;
import java.text.*;
import experiment1.*;
import experiment2.*;
import experiment3.*;
/**
 * This class implements a gourmet coffee system.
 *
 * @author author name
 * @version 1.1.0
 * @see Product
 * @see Coffee
 * @see CoffeeBrewer
 * @see Catalog
 * @see OrderItem
 * @see Order
 * @see SalesFormatter
 * @see PlainTextSalesFormatter
 * @see HTMLSalesFormatter
 * @see XMLSalesFormatter
 * @see CatalogLoader
 * @see FileCatalogLoader
 */
public class GourmetCoffee  {

	private static BufferedReader  stdIn =
		new  BufferedReader(new  InputStreamReader(System.in));
	private static PrintWriter  stdOut = new  PrintWriter(System.out, true);
	private static PrintWriter  stdErr = new  PrintWriter(System.err, true);
	private Catalog  catalog;
	private Sales  sales;

	private SalesFormatter salesFormatter;

	/**
	 * Loads catalog data from a file and starts the application.
	 * <p>
	 * The name of the file is specified in the command arguments.
	 * </p>
	 *
	 * @param args  String arguments.
	 * @throws IOException if there are errors in the input.
	 */
	public static void  main(String[]  args) throws IOException  {
		Catalog catalog = null;

		if (args.length != 1) {
			stdErr.println("Usage: java GourmetCoffee filename");
		} else {
			try {
				catalog =
					(new FileCatalogLoader()).loadCatalog(args[0]);
			} catch (FileNotFoundException fnfe) {
				stdErr.println("The file does not exist");

				System.exit(1);

			} catch (DataFormatException dfe) {
				stdErr.println("The file contains malformed data: "
				               + dfe.getMessage());

				System.exit(1);
			}

			GourmetCoffee  application =
				new GourmetCoffee(catalog);
			application.run();
		}
	}

	/**
	 * Constructs a <code>GourmetCoffee</code> object.
	 * Initializes the catalog data with the value specified
	 * in the parameter.
	 *
	 * @param initialCatalog a product catalog
	 */
	private GourmetCoffee(Catalog initialCatalog) {

		this.catalog = initialCatalog;
		this.sales = new Sales();
		this.salesFormatter =
			PlainTextSalesFormatter.getSingletonInstance();

		loadSales();
	}

	/**
	 * Initializes the sales object.
	 */
	private void loadSales() {

		Order orderOne = new Order();
		Product productOne = this.catalog.getProduct("C001");
		
		if (productOne != null) {
			orderOne.addItem(new OrderItem(productOne, 5));
			this.sales.addOrder(orderOne);
		}

		Order orderTwo = new Order();
		Product productTwo = this.catalog.getProduct("C002");
		Product productThree = this.catalog.getProduct("A001");

		if ((productTwo != null) && (productThree != null)) {
			orderTwo.addItem(new OrderItem(productTwo, 2));
			orderTwo.addItem(new OrderItem(productThree, 2));
			this.sales.addOrder(orderTwo);
		}

		Order orderThree = new Order();
		Product productFour = this.catalog.getProduct("B002");

		if (productFour != null) {
			orderThree.addItem(new OrderItem(productFour, 1));
			this.sales.addOrder(orderThree);
		}
	}

	/**
	 * Presents the user with a menu of options and executes the
	 * selected task.
	 */
	private void run() throws IOException  {

		int  choice = getChoice();

		while (choice != 0)  {
			if (choice == 1)  {
				displayCatalog();
			} else if (choice == 2)  {
				this.salesFormatter =
					PlainTextSalesFormatter.getSingletonInstance();
				writeFile(
					readFilename(),
					this.salesFormatter.formatSales(this.sales));
			} else if (choice == 3)  {
				this.salesFormatter =
					HTMLSalesFormatter.getSingletonInstance();
				writeFile(
					readFilename(),
					this.salesFormatter.formatSales(this.sales));
			} else if (choice == 4)  {
				this.salesFormatter =
					XMLSalesFormatter.getSingletonInstance();
				writeFile(
					readFilename(),
					this.salesFormatter.formatSales(this.sales));
			}

			choice = getChoice();
		}
	}

	/**
	 * Displays a menu of options and verifies the user's choice.
	 *
	 * @return an integer in the range [0,7]
	 */
	private int  getChoice() throws IOException  {

		int  input;

		do  {
			try  {
				stdErr.println();
				stdErr.print("[0]  Quit\n"
				             + "[1]  Display Catalog\n"
				             + "[2]  Save sales (Plain Text)\n"
				             + "[3]  Save sales (HTML)\n"
				             + "[4]  Save sales (XML)\n"
				             + "choice> ");
				stdErr.flush();

				input = Integer.parseInt(stdIn.readLine());

				stdErr.println();

				if (0 <= input && 4 >= input)  {
					break;
				} else {
					stdErr.println("Invalid choice:  " + input);
				}
			} catch (NumberFormatException  nfe)  {
				stdErr.println(nfe);
			}
		}  while (true);

		return  input;
	}

	/**
	 * Displays the catalog.
	 */
	private void displayCatalog() {

		int size = this.catalog.getNumberOfProducts();

		if (size == 0) {
			stdErr.println("The catalog is empty");
		} else {
			for (Product product : this.catalog) {
				stdOut.println(product.getCode() + " "
				               + product.getDescription());
			}
		}
	}

	/**
	 * Creates a new file (which has the specified name) and writes
	 * the specified string to the new file.
	 *
	 * @param filename name of the file that will store the data
	 * @param content data to be stored
	 */
	private void writeFile(String filename, String content)
		throws IOException {

		/* PLACE YOUR CODE HERE */
        File file=new File(filename);
        if(file.exists()){
            file.delete();
        }
        file.createNewFile();
        FileWriter filewriter=new FileWriter(filename,true);
        BufferedWriter filewriter1=new BufferedWriter(filewriter);
        filewriter1.write(content);
        filewriter1.close();
        filewriter.close();
	}

	/**
	 * Prompts the user for a filename (the name of the file that
	 * will store the sales information) and returns the user's
	 * response.
	 *
	 * @return name of a file
	 */
	private  String readFilename() throws IOException  {

		stdErr.print("Filename> ");
		stdErr.flush();

		return stdIn.readLine();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只super羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值