我有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);
}
最佳答案
似乎OrderCatalogue构造函数抛出FileNotFoundException。您可以在Shopping构造函数中初始化目录并捕获异常,或将其声明为引发FileNotFoundException。
public Shopping() throws FileNotFoundException
{
this.catalogue= new OrderCatalogue();
要么
public Shopping()
{
try{
this.catalogue= new OrderCatalogue();
}catch(FileNotFoundException e)
blah blah
}