zsh669 2022-05-21 18:02 采纳率: 87.5%
浏览 58

在读取文件并进行测试时出错

再做咖啡馆java项目时

以下是读取文件的代码FileCatalogLoader

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;


public class FileCatalogLoader implements CatalogLoader{
    private Product readProduct(String line)
            throws DataFormatException{
        StringTokenizer token=new StringTokenizer(line,"_");
        if(token.countTokens()!=6) {
            throw new DataFormatException(line);
        }else {
            try {
                String prefix=token.nextToken();
                return new Product(token.nextToken(),token.nextToken(),Double.parseDouble(token.nextToken()));
            }
            catch(NumberFormatException  nfe) {
                throw new DataFormatException(line);
            }
        }
    }
    
    private Coffee readCoffee(String line)
            throws DataFormatException{
                StringTokenizer token=new StringTokenizer(line,"_");
                if(token.countTokens()!=10) {
                    throw new DataFormatException(line);
                }else {
                    try {
                        String prefix=token.nextToken();
                        return new Coffee(token.nextToken(),token.nextToken(),Double.parseDouble(token.nextToken()),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken(),token.nextToken());
                    }
                    catch(NumberFormatException  nfe) {
                        throw new DataFormatException(line);
                    }
                }
    }
        
    private CoffeeBrewer readCoffeeBrewer(String line) 
            throws DataFormatException{
        StringTokenizer token=new StringTokenizer(line,"_");
        if(token.countTokens()!=7) {
            throw new DataFormatException(line);
        }else {
            try {
                String prefix=token.nextToken();
                return new CoffeeBrewer(token.nextToken(),token.nextToken(),Double.parseDouble(token.nextToken()),token.nextToken(),token.nextToken(),Integer.parseInt(token.nextToken()));
            }
            catch(NumberFormatException  nfe) {
                throw new DataFormatException(line);
            }
        }
}
    
    public Catalog loadCatalog(String filename)
            throws FileNotFoundException, 
                   IOException,
                   DataFormatException{
        Catalog catalog=new Catalog();
        BufferedReader read= new BufferedReader(new FileReader(filename));
        String line =read.readLine();
        while(line!=null) {
            Product item=null;
            if(line.startsWith("Product")) {
                item=readProduct(line);
            }
            else if(line.startsWith("Coffee")) {
                item=readCoffee(line);
            }
            else if(line.startsWith("CoffeeBrewer")) {
                item=readCoffeeBrewer(line);
            }
            else {
                throw new DataFormatException(line);
            }
            catalog.addProduct(item);
            line =read.readLine();
        }
        return catalog;
}

}


import java.io.*;
import java.util.*;

/**
 * Tests the class <code>FileCatalogLoader</code>
 *
 * @author author name
 * @version 1.0.0
 * @see FileCatalogLoader
 */
public class  TestFileCatalogLoader  {

    /* Standard output stream */
    private static PrintWriter  stdOut = new  PrintWriter(System.out, true);

    /* Standard error stream */
    private static PrintWriter  stdErr = new  PrintWriter(System.err, true);

    /**
     * Tests methods of class {@link FileCatalogLoader}
     *
     * @param args  not used.
     * @throws IOException  if an I/O error occurs.
     */
    public static void main (String args[]) throws IOException {

        TestFileCatalogLoader tester =
            new TestFileCatalogLoader();

        tester.testLoadCatalog();
        stdOut.println("All tests passed");
    }

    /**
     * Displays a message in the standard error stream if the value specified
     * by parameter <code>condition<code> is <code>false</code>.
     *
     * @param message  the error message.
     * @param condition  the test condition.
     * @return the value of <code>condition</code>
     */
    public static void assertTrue(String message, boolean condition) {

        if (!condition) {
            stdErr.print("** Test failure ");
            stdErr.println(message);

            System.exit(1);
        }

    }
    
    /**
     * Displays a message in the standard error stream.
     *
     * @param message  the error message.
     * @return <code>false</code>;
     */
    public static void fail(String message) {

        stdErr.print("** Test failure ");
        stdErr.println(message);

        System.exit(1);
    }

    /**
     * Tests the method <code>loadCatalog</code>.
     *
     * @return <code>true</code> if all test passed; otherwise returns
     *         <code>false</code>.
     * @throws IOException  if an I/O error occurs.
     */
    public void testLoadCatalog() throws IOException {

        CatalogLoader loader = new FileCatalogLoader();
            
        try {
            // Testing an empty file
            Catalog emptyCatalog =
                loader.loadCatalog("D:\\学习\\面向对象\\JAVA\\面向对象\\作业\\项目\\Coffee//empty.dat");
                
            assertTrue("1, testing method read with an empty file",
                emptyCatalog instanceof Catalog);
            assertTrue("2, testing method read with an empty file"
                + emptyCatalog.getNumberOfProducts() + " products loaded",
                emptyCatalog.getNumberOfProducts() == 0);
            
            // Testing a not empty file
            Catalog catalog =
                loader.loadCatalog("catalog.dat");
    
            assertTrue("3, testing method loadCatalog",
                catalog instanceof Catalog);
            assertTrue("4, testing method loadCatalog: "
                + catalog.getNumberOfProducts() + " products loaded",
                catalog.getNumberOfProducts() == 26);
            
            // Testing product C001
            Product product = catalog.getProduct("C001");
            
            assertTrue("5, testing method loadCatalog" + product.toString(),
                product instanceof Coffee);
            
            Coffee coffeeC001 = (Coffee) product;
                
            assertTrue("6, testing method loadCatalog: " + 
                coffeeC001.toString(),
                coffeeC001.getCode().equals("C001") &&
                coffeeC001.getDescription().equals("Colombia, Whole, 1 lb") &&
                coffeeC001.getPrice() == 17.99 &&
                coffeeC001.getOrigin().equals("Colombia") &&
                coffeeC001.getRoast().equals("Medium") &&
                coffeeC001.getFlavor().equals("Rich and Hearty")  &&
                coffeeC001.getAroma().equals("Rich") &&
                coffeeC001.getAcidity().equals("Medium") &&
                coffeeC001.getBody().equals("Full"));
            
            // Testing product C002
            product = catalog.getProduct("C002");
            
            assertTrue("7, testing method loadCatalog: " + product.toString(),
                product instanceof Coffee);
            
            Coffee coffeeC002 = (Coffee) product;
                
            assertTrue("8, testing method loadCatalog: " + 
                coffeeC002.toString(),
                coffeeC002.getCode().equals("C002") &&
                coffeeC002.getDescription().equals("Colombia, Ground, 1 lb") &&
                coffeeC002.getPrice() == 18.75 &&
                coffeeC002.getOrigin().equals("Colombia") &&
                coffeeC002.getRoast().equals("Medium") &&
                coffeeC002.getFlavor().equals("Rich and Hearty")  &&
                coffeeC002.getAroma().equals("Rich") &&
                coffeeC002.getAcidity().equals("Medium") &&
                coffeeC002.getBody().equals("Full"));
                
            // Testing product A001
            product = catalog.getProduct("A001");
            
            assertTrue("9, testing method loadCatalog: " + product.toString(),
                product instanceof Product);
                
            assertTrue("10, testing method loadCatalog: " + 
                product.toString(),
                product.getCode().equals("A001") &&
                product.getDescription().equals("Almond Flavored Syrup") &&
                product.getPrice() == 9.0);
                
            // Testing product B002
            product = catalog.getProduct("B002");
            
            assertTrue("11, testing method loadCatalog: " + product.toString(),
                product instanceof CoffeeBrewer);
    
            CoffeeBrewer brewerB002 = (CoffeeBrewer) product;
            
            assertTrue("12, testing method loadCatalog: " + 
                brewerB002.toString(),
                brewerB002.getCode().equals("B002") &&
                brewerB002.getDescription().equals("Coffee Brewer, 2 Warmers") &&
                brewerB002.getPrice() == 200.0 &&
                brewerB002.getModel().equals("Brewer 200") &&
                brewerB002.getWaterSupply().equals("Pourover") &&
                brewerB002.getNumberOfCups() == 12);
                
        } catch (Exception e) {
            fail("13, testing method loadCatalog: " + e.getMessage());
        }
    }
}

测试时报错
通过直接编译和自己调试产生的错误不同
**一下是FileCatalogLoader所读取的文件内容catalog.dat

  • <input type="checkbox" disabled="" />
  • <input type="checkbox" disabled="" />
  • <input type="checkbox" disabled="" /> **
    Coffee_C001_Colombia, Whole, 1 lb_17.99_Colombia_Medium_Rich and Hearty_Rich_Medium_Full
    Coffee_C002_Colombia, Ground, 1 lb_18.75_Colombia_Medium_Rich and Hearty_Rich_Medium_Full
    Coffee_C003_Italian Roast, Whole, 1 lb_16.80_Latin American Blend_Italian Roast_Dark and heavy_Intense_Low_Medium
    Coffee_C004_Italian Roast, Ground, 1 lb_17.55_Latin American Blend_Italian Roast_Dark and heavy_Intense_Low_Medium
    Coffee_C005_French Roast, Whole, 1 lb_16.80_Latin American Blend_French Roast_Bittersweet, full intense_Intense, full_None_Medium
    Coffee_C006_French Roast, Ground, 1 lb_17.55_Latin American Blend_French Roast_Bittersweet, full intense_Intense, full_None_Medium
    Coffee_C007_Guatemala, Whole, 1 lb_17.99_Guatemala_Medium_Rich and complex_Spicy_Medium to high_Medium to full
    Coffee_C008_Guatemala, Ground, 1 lb_18.75_Guatemala_Medium_Rich and complex_Spicy_Medium to high_Medium to full
    Coffee_C009_Sumatra, Whole, 1 lb_19.99_Sumatra_Medium_Vibrant and powdery_Like dark chocolate_Gentle_Rich and full
    Coffee_C010_Sumatra, Ground, 1 lb_20.50_Sumatra_Medium_Vibrant and powdery_Like dark chocolate_Gentle_Rich and full
    Coffee_C011_Decaf Blend, Whole, 1 lb_16.80_Latin American Blend_Dark roast_Full, roasted flavor_Hearty_Bold and rich_Full
    Coffee_C012_Decaf Blend, Ground, 1 lb_17.55_Latin American Blend_Dark roast_Full, roasted flavor_Hearty_Bold and rich_Full
    Brewer_B001_Home Coffee Brewer_150.00_Brewer 100_Pourover_6
    Brewer_B002_Coffee Brewer, 2 Warmers_200.00_Brewer 200_Pourover_12
    Brewer_B003_Coffee Brewer, 3 Warmers_280.00_Brewer 210_Pourover_12
    Brewer_B004_Commercial Coffee, 20 Cups_380.00_Quick Coffee 100_Automatic_20
    Brewer_B005_Commercial Coffee, 40 Cups_480.00_Quick Coffee 200_Automatic_40
    Product_A001_Almond Flavored Syrup_9.00
    Product_A002_Irish Creme Flavored Syrup_9.00
    Product_A003_Mint Flavored syrup_9.00
    Product_A004_Caramel Flavored Syrup_9.00
    Product_A005_Gourmet Coffee Cookies_12.00
    Product_A006_Gourmet Coffee Travel Thermo_18.00
    Product_A007_Gourmet Coffee Ceramic Mug_8.00
    Product_A008_Gourmet Coffee 12 Cup Filters_15.00
    Product_A009_Gourmet Coffee 36 Cup Filters_45.00

在其中涉及到代码

import java.util.Iterator;
import java.util.Vector;

public class Catalog {
    private Vector products;
    
    
    public Catalog() {
        products=new Vector();
    }
    
    public void addProduct(Product product) {
        products.add(product);
    }
    
    public Iterator getProductsIterator()  {
        return products.iterator();
        
    }
    
    public Product getProduct(String code) {
        Iterator it=products.iterator();
        
        while(it.hasNext()) {
            Product pro=(Product)it.next();
            if(pro.getCode()==code) {
                return pro;
            }
        }
        return null;
    }
    
    
    public int getNumberOfProducts() {
        return products.size();
    }
    public String[] getCodes() {
        String[] str=null;
        int i=0;
        Iterator it=products.iterator();
        while(it.hasNext()) {
            Product pro=(Product)it.next();
            str[i]=str[i]+pro.getCode();
            i++;
        }
        return str;
    }
}


package coffee;

import  java.awt.*;
import  javax.swing.*;

/**
 * This class models a coffee product. It extends
 * {@link Product} and adds the following information:
 * <ol>
 * <li>the origin of the coffee, a <code>String</code></li>
 * <li>the roast of the coffee, a <code>String</li>
 * <li>the flavor of the coffee, a <code>String</li>
 * <li>the aroma of the coffee, a <code>String</li>
 * <li>the acidity of the coffee, a <code>String</li>
 * <li>the body of the product, a <code>double</li>
 * </ol>
 *
 * @author author name
 * @version  1.0.0
 * @see Product
 */
public class Coffee extends Product  {

    /* Origin of the coffee. */
    private String  origin;

    /* Roast of the coffee. */
    private String  roast;

    /* Flavor of the coffee. */
    private String  flavor;

    /* Aroma of the coffee. */
    private String  aroma;

    /* Acidity of the coffee.*/
    private String  acidity;

    /* Body of the coffee */
    private String  body;

    /**
     * Constructs a <code>Coffee</code> object.
     *
     * @param initialCode  the code of the product.
     * @param initialDescription  a short description of the product.
     * @param initialPrice  the price of the product.
     * @param initialOrigin the origin of coffee.
     * @param initialRoast the kind of roast of the coffee.
     * @param initialFlavor  the flavor of the coffee.
     * @param initialAroma  the aroma of the coffee.
     * @param initialAcidity  the acidity of the coffee.
     * @param initialBody  the body of the coffee.
     */
    public Coffee(String initialCode, String initialDescription,
            double  initialPrice, String initialOrigin,
            String initialRoast, String initialFlavor,
            String initialAroma, String initialAcidity,
            String initialBody) {

        super(initialCode, initialDescription, initialPrice);

        origin = initialOrigin;
        roast = initialRoast;
        flavor = initialFlavor;
        aroma = initialAroma;
        acidity = initialAcidity;
        body = initialBody;
    }

    /**
     * Returns the origin of this coffee.
     *
     * @return  the origin of this coffee.
     */
    public String  getOrigin()  {

        return  origin;
    }

    /**
     * Returns the roast of this coffee.
     *
     * @return  the roast of this coffee.
     */
    public String  getRoast()  {

        return  roast;
    }

    /**
     * Returns the flavor of this coffee.
     *
     * @return  the flavor of this coffee.
     */
    public String  getFlavor()  {

        return  flavor;
    }

    /**
     * Returns the aroma of this coffee.
     *
     * @return  the aroma of this coffee.
     */
    public String  getAroma()  {

        return  aroma;
    }

    /**
     * Returns  the acidity of this coffee.
     *
     * @return  the acidity of this coffee.
     */
    public String  getAcidity()  {

        return  acidity;
    }

    /**
     * Returns the body of this coffee.
     *
     * @return  the body of this coffee.
     */
    public String  getBody()  {

        return  body;
    }

    /**
     * Returns the string representation of this coffee.
     *
     * @return  the string representation of this coffee.
     */
    public String  toString()  {

        return super.toString() + "_" + getOrigin() + "_" + getRoast() + "_"
               + getFlavor() + "_" + getAroma()    + getAcidity() + "_"
               + getBody();
    }

    /**
     * Obtains a {@link JPanel} object with the information of this
     * coffee product.
     *
     * @return a {@link JPanel} with the information of this coffee product.
     */
    public JPanel getPanel() {

        
        JLabel origin=new JLabel("Origin");
        JTextField originText=new JTextField(10);
        JLabel roast=new JLabel("Roast");
        JTextField roastText=new JTextField(10);
        JLabel flavor=new JLabel("Flavor");
        JTextField flavorText=new JTextField(10);
        JLabel aroma=new JLabel("Aroma");
        JTextField aromaText=new JTextField(10);
        JLabel acidity=new JLabel("Acidity");
        JTextField acidityField=new JTextField(10);
        JLabel body=new JLabel("Body");
        JTextField bodyText=new JTextField(10);
        JPanel panel=super.getPanel();
        panel.add(origin);
        panel.add(originText);
        panel.add(roast);
        panel.add(roastText);
        panel.add(flavor);
        panel.add(flavorText);
        panel.add(aroma);
        panel.add(aromaText);
        panel.add(acidity);
        panel.add(acidityField);
        panel.add(body);
        panel.add(bodyText);
        
        

        return panel; // REMOVE; USED SO THIS FILE COMPILES
    }
}

import  java.awt.*;
import  javax.swing.*;

/**
 * This class models a coffee brewer. It extends {@link Product} and adds the
 * following information:
 * <ol>
 * <li>the model of the coffee brewer, a <code>String</code></li>
 * <li>the water supply ("Pour-over" or "Automatic")</li>
 * <li>the capacity expressed in number of cups, a <code>int</code></li>
 * </ol>
 *
 * @author author name
 * @version  1.0.0
 * @see Product
 */
public class CoffeeBrewer extends Product  {

    /* Model of the coffee brewer. */
    private String  model;

    /* The water supply of the coffee brewer ("Pour-over" or "Automatic"). */
    private String  waterSupply;

    /* The capacity expressed in number of cups. */
    private int  numberOfCups;

    /**
     * Constructs a <code>CoffeeBrewer</code> object.
     *
     * @param initialCode  the code of the product.
     * @param initialDescription  a short description of the product.
     * @param initialPrice  the price of the product.
     * @param initialModel  the model of the coffee brewer.
     * @param initialWaterSupply  the water supply is ("Pour-over" or
     *                        "Automatic").
     * @param initialNumberOfCups  the capacity expressed in number of cups.
     */
    public CoffeeBrewer(String initialCode, String initialDescription,
            double  initialPrice, String initialModel,
            String initialWaterSupply, int initialNumberOfCups)  {

        super(initialCode, initialDescription, initialPrice);

        model = initialModel;
        waterSupply = initialWaterSupply;
        numberOfCups = initialNumberOfCups;
    }

    /**
     * Returns the model of this coffee brewer.
     *
     * @return  the model of this coffee brewer.
     */
    public String  getModel()  {

        return  model;
    }

    /**
     * Returns the type of water supply.
     *
     * @return  returns "Pour-over" or "Automatic".
     */
    public String  getWaterSupply()  {

        return  waterSupply;
    }

    /**
     * Returns the capacity of this coffee brewer expressed in number of cups.
     *
     * @return  the capacity of this coffee brewer expressed in number of cups.
     */
    public int  getNumberOfCups()  {

        return  numberOfCups;
    }

    /**
     * Returns the string representation of this coffee brewer.
     *
     * @return  the string representation of this coffee brewer.
     */
    public String  toString()  {

        return super.toString() + "_" + getModel() + "_" + getWaterSupply()
               + "_" + getNumberOfCups();
    }

    /**
     * Obtains a {@link JPanel} object with the information of this coffee
     * brewer.
     *
     * @return a <code>JPanel</code> with the information of this coffee brewer.
     */
    public JPanel getPanel() {

        JPanel panel=super.getPanel();
        JLabel model=new JLabel("Model");
        JLabel water=new JLabel("Source of Water");
        JLabel cups=new JLabel("Numbers of Cups");
        JTextField modelText=new JTextField(10);
        JTextField waterText=new JTextField(10);
        JTextField cupsText=new JTextField(10);
        panel.add(model);
        panel.add(modelText);
        panel.add(water);
        panel.add(waterText);
        panel.add(cups);
        panel.add(cupsText);
        return panel; // REMOVE; USED SO THIS FILE COMPILES
    }
}

import  java.awt.*;
import  javax.swing.*;

/**
 * This class models a product sold by the Gourmet Coffee store.
 * It contains the following information:
 * <ol>
 * <li>the code of the product, a <code>String</code></li>
 * <li>a short description of the product, a <code>String</code></li>
 * <li>the price of the product, a <code>double</code></li>
 * </ol>
 *
 * @author author name
 * @version  1.0.0
 */
public class Product {

    /* Code of the product. */
    private String  code;

    /* Description of the product. */
    private String  description;

    /* Price of the product. */
    private double  price;

    /**
     * Constructs a <code>Product</code> object.
     *
     * @param initialCode  the code of the product.
     * @param initialDescription  the description of the product.
     * @param initialPrice  the price of the product.
     */
    public Product(String initialCode, String initialDescription,
                   double initialPrice)  {

        code = initialCode;
        description = initialDescription;
        price = initialPrice;
    }

    /**
     * Returns the code of this product.
     *
     * @return  the code of this product.
     */
    public String  getCode()  {

        return  code;
    }

    /**
     * Returns the description of this product.
     *
     * @return  the descripton of this product.
     */
    public String  getDescription()  {

        return  description;
    }

    /**
     * Returns the price of this product.
     *
     * @return  price of this product.
     */
    public double  getPrice()  {

        return  price;
    }

    /**
     * Returns <code>true</code> if code of this product is
     * equal to code of the argument.
     * </p>
     *
     * @param object  object with which this product is compared.
     * @return  <code>true</code> if code of this product is
     *          equal to code of the argument; <code>false</code> otherwise.
     */
    public boolean  equals(Object  object)  {

        return object instanceof Product
               && getCode().equals(((Product) object).getCode());
    }

    /**
     * Returns the string representation of this product.
     *
     * @return  the string representation of this product.
     */
    public String  toString()  {

        return  getCode() + "_" + getDescription() + "_" + getPrice();
    }

    /**
     * Obtains a {@link JPanel} object with the information of this product.
     *
     * @return a <code>JPanel</code> with the information of this product.
     */
    public JPanel getPanel() {

        JLabel code;
        JLabel description;
        JLabel price;
        JTextField codeText=new JTextField(10);
        JTextField descriptionText=new JTextField(10);
        JTextField priceText=new JTextField(10);
        price=new JLabel("Price");
        code=new JLabel("code");
        description=new JLabel("Description");
        JPanel panel=new JPanel();
        panel.setLayout(new GridLayout(9,2));
        panel.add(code);
        panel.add(codeText);
        panel.add(description);
        panel.add(descriptionText);
        panel.add(price);
        panel.add(priceText);

        return panel; // REMOVE; USED SO THIS FILE COMPILES
    }
}

直接运行的错误:** Test failure 13, testing method loadCatalog: Brewer_B001_Home Coffee Brewer_150.00_Brewer 100_Pourover_6
debug的错误:** Test failure 13, testing method loadCatalog: Coffee_C001_Colombia, Whole, 1 lb_17.99_Colombia_Medium_Rich and Hearty_Rich_Medium_Full

  • 写回答

1条回答 默认 最新

  • CSDN专家-sinJack 2022-05-21 22:47
    关注

    控制台的报错信息是什么。
    找到报错所在的代码行处。

    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 5月21日

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀