对于类分配,我需要将一个对象写入文件。我们的教授给了我们一段代码来完成此操作,但是显然这是错误的,因为我遇到了错误。这是我的代码。
class InvMaintenance {
//create an OutputStream to write data to a file
FileOutputStream fos = new FileOutputStream(inven.dat);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
final long MAX_SIZE = 100; //constant for array length
Inventory cInventory = new Inventory(MAX_SIZE); //instantiate Inventory object
oos.writeObject(cInventory); //write initial Inventory to file
public static void main(String[] args) {
//Output options
/* Inventory Maintenance
1) Add Item
2) Remove Item
3) Sell Item
4) Receive Item
5) Display Inventory
6) Quit
Please Select NUMBER: */
//switch on options
//call appropriate method
oos.writeObject(cInventory);
oos.close();
}
}
我的错误发生在
oos.writeObject(cInventory);
行上Item.java:150:预期
oos.writeObject(cInventory);//将初始库存写入文件
^
Item.java:150:预期
oos.writeObject(cInventory);//将初始库存写入文件
^
2个错误
是的,由于某种原因,这是两个完全相同的独立错误。
任何帮助调试将不胜感激。怎么了?
最佳答案
必须在主方法中
//create an OutputStream to write data to a file
FileOutputStream fos = new FileOutputStream(inven.dat);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
Inventory cInventory = new Inventory(MAX_SIZE); //instantiate Inventory object
更改代码:
class InvMaintenance {
final static long MAX_SIZE = 100; //constant for array length
public static void main(String[] args)
{
//Output options
/* Inventory Maintenance
1) Add Item
2) Remove Item
3) Sell Item
4) Receive Item
5) Display Inventory
6) Quit
Please Select NUMBER: */
//switch on options
//call appropriate method
//create an OutputStream to write data to a file
FileOutputStream fos = new FileOutputStream(inven.dat);
BufferedOutputStream bos = new BufferedOutputStream(fos);
ObjectOutputStream oos = new ObjectOutputStream(bos);
Inventory cInventory = new Inventory(MAX_SIZE); //instantiate Inventory object
oos.writeObject(cInventory);
oos.close();
}
}
提示:将常量更改为final static long ..如果您使用static,则值将在编译时复制
提示2:照顾异常..