0

我有 2 个文件,其中 1(OrderCatalogue.java)读取外部文件的内容和 2(如下)。但是对于“OrderCatalogue catalogue= new OrderCatalogue();”这一行,我遇到了“必须捕获或声明要抛出 FileNotFoundException”错误。我明白这一点,因为它不是一种方法。但是如果我尝试将它放在一个方法中,“getCodeIndex”和“checkOut”方法下的代码不能与“包目录不存在”的错误消息一起使用。任何人都知道如何编辑我的代码以使其工作?谢谢!!

public class Shopping {

OrderCatalogue catalogue= new OrderCatalogue();
ArrayList<Integer> orderqty = new ArrayList<>(); //Create array to store user's input of quantity
ArrayList<String> ordercode = new ArrayList<>(); //Create array to store user's input of order number

    public int getCodeIndex(String code)
    {    
        int index = -1;

        for (int i =0;i<catalogue.productList.size();i++)
        {            
            if(catalogue.productList.get(i).code.equals(code))
            {
            index = i;
            break;
            }
        }
        return index;
    }
    public void checkout()
    {
         DecimalFormat df = new DecimalFormat("0.00");
         System.out.println("Your order:");
         for(int j=0;j<ordercode.size();j++)
         {
            String orderc = ordercode.get(j);

            for (int i =0;i<catalogue.productList.size();i++)
            {
                if(catalogue.productList.get(i).code.equals(orderc))
                {
                    System.out.print(orderqty.get(j)+" ");
                    System.out.print(catalogue.productList.get(i).desc);
                    System.out.print(" @ $"+df.format(catalogue.productList.get(i).price)); 
                }
            }   
        }

    }

这是我的 OrderCatalogue 文件

public OrderCatalogue() throws FileNotFoundException

{

    //Open the file "Catalog.txt"
           FileReader fr = new FileReader("Catalog.txt");
           Scanner file = new Scanner(fr);


           while(file.hasNextLine())
           {
               //Read in the product details in the file
               String data = file.nextLine();
               String[] result = data.split("\\, "); 

               String code = result[0];
               String desc = result[1];
               String price = result[2];
               String unit = result[3];

               //Store the product details in a vector
               Product a = new Product(desc, code, price, unit);

               productList.add(a);
           }
4

1 回答 1

2

似乎 OrderCatalogue 构造函数抛出 FileNotFoundException。您可以在 Shopping 构造函数中初始化目录并捕获异常或将其声明为抛出 FileNotFoundException。

public Shopping() throws FileNotFoundException
{
        this.catalogue= new OrderCatalogue();

或者

public Shopping()
    {
            try{
                this.catalogue= new OrderCatalogue();
            }catch(FileNotFoundException e)
                blah blah
            }
于 2013-02-16T04:32:02.293 回答