java.lang.ClassCastException: infrastructure cannot be cast to terrain
at p2_assign_version2.main(p2_assign_version2.java:98)
这是我尝试构建文件时不断打印的错误。由于这个错误,我无法在我的 terrain.txt 中打印我的所有数据
这里有谁知道我可以如何解决这个错误?
以下是导致错误出现的代码集
File terrain=new File("terrain.txt"); //To create file
boolean tExist=terrain.exists();
terrain[]terrains = new terrain[100];
if(!tExist)
{
try
{
FileOutputStream fos = new FileOutputStream("terrain.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
terrains[0] = new terrain("Grass", true);
oos.writeObject(terrains[0]);
terrains[1] = new terrain("Water", false);
oos.writeObject(terrains[1]);
terrains[2] = new terrain("Pavement", false);
oos.writeObject(terrains[2]);
terrains[3] = new terrain("Road", false);
oos.writeObject(terrains[4]);
terrains[5] = new terrain("Drainage", false);
oos.writeObject(terrains[5]);
terrains[6] = new terrain("Hill", false);
oos.writeObject(terrains[6]);
terrains[7] = new terrain("Bushes", false);
oos.writeObject(terrains[7]);
terrains[8] = new terrain("Tree", false);
oos.writeObject(terrains[8]);
oos.flush();
oos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
else
{
try
{
FileInputStream fis=new FileInputStream("terrain.txt");
ObjectInputStream ois=new ObjectInputStream(fis);
for (p=0; p<terrains.length; p++)
{
if(terrains[p] == null)
{
//this is the line that causes error to be printed//
terrains[p] = (terrain) ois.readObject();
}
}
ois.close();
}
catch(EOFException eof)
{
}
catch(FileNotFoundException fnfe)
{
System.out.println("There seems to be a problem reading from the file");
}
catch(Exception e)
{
e.printStackTrace();
}
}