我有 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);
}