gpt4 book ai didi

Java 需要 writeObject()

转载 作者:行者123 更新时间:2023-12-02 08:00:41 26 4
gpt4 key购买 nike

对于类作业,我需要将对象写入文件。我们的教授给了我们一段代码来完成这个任务,但显然它是错误的,因为我收到了一个错误。这是我的代码。

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: <identifier> expected    oos.writeObject(cInventory);            //write initial Inventory to file                      ^Item.java:150: <identifier> expected    oos.writeObject(cInventory);            //write initial Inventory to file                                 ^2 errors

是的,出于某种原因,它说这是两个独立的错误......完全相同。

任何调试帮助将不胜感激。怎么了?

最佳答案

必须在主方法中

//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:处理异常..

关于Java <identifier> 需要 writeObject(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8960277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com