0

我想我什至不必提及我是 Java 初学者,这是作业的一部分。它必须非常明显。我想要的是在公寓预订系统中计算占用的房间,但我完全被卡住了。我真的不知道如何保存 aptA、aptB 和 aptM 的值。每次重新启动程序时,我都需要加载它们。现在我收到以下错误:

线程“主”java.lang.RuntimeException 中的异常:无法编译的源代码 - 错误的 sym 类型:Apartments1.Person.loadObject(Person.java:348) 处的 ObjectInputStream.Departments1.Booking.main(Booking.java:24) Java 结果: 1

我有一种感觉,虽然我的方法可能是错误的,但这是我在拼命地测试了其他几个解决方案之后最终结束的......现在一切都变得一团糟,我即将放弃。

     //creating the object   
     public static void addRoomCounter(){
     Person roomCounter = new Person(); 
     roomCounter.addAptA();
     roomCounter.addAptB();
     roomCounter.addAptM();

     //adding it to arraylist
    ArrayList<Person> roomList = new ArrayList<Person>();
roomList.add(roomCounter);

    //saving it to file
     try{
     FileOutputStream saveFile = new FileOutputStream("Roomcounter.txt");
     ObjectOutputStream save = ObjectOutputStream(saveFile); //cannot find symbol
     save.writeObject(roomCounter);
     save.close();
    }catch(Exception exc){
    }
    }


    public int addAptA(){
    return aptA;
    }
    public int addAptB(){
    return aptB;
    }
    public int addAptM(){
    return aptM;
    }

    //loading object
public static void loadObject(){
    try{
    FileInputStream saveFile = new FileInputStream("Roomcounter.txt");
ObjectInputStream restore = ObjectInputStream(saveFile); //cannot find symbol
Object roomCounter = restore.readObject();
    int aptA = (int) restore.readObject();
    int aptB = (int) restore.readObject();
    int aptM = (int) restore.readObject();
restore.close();
    }catch(IOException | ClassNotFoundException exc){
    }
    }
4

1 回答 1

1

问题在于您的阅读障碍。您正在阅读该对象,但将其类型转换到int它应该在的位置Person。IE

public static void loadObject(){
try{
  FileInputStream saveFile = new FileInputStream("Roomcounter.txt");
  ObjectInputStream restore = ObjectInputStream(saveFile); //cannot find symbol
  Person roomCounter = (Person) restore.readObject();
  int aptA = (int) restore.getAptA();
  int aptB = (int) restore.getAptB();
  int aptM = (int) restore.getAptC()();
  restore.close();
  }catch(IOException | ClassNotFoundException exc){
   exc.printStackTrace();
}
}

在您的示例中,您从文件中的序列化对象中读取了三次对象。相反,您需要阅读一次然后解决。

于 2013-07-12T19:37:54.880 回答