0
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();
}
}
1)爲了更快提供幫助,請發佈[SSCCE](http://sscce.org/)。 2)將catch(Exception e){..']形式的代碼更改爲catch(Exception e){e.printStackTrace(); //非常翔實! ..' – 2013-05-11 11:19:42
很明顯'地形'不是從'基礎設施'派生的。 – 2013-05-11 11:34:38
'terrains [3] =新地形(「道路」,假); oos.writeObject(terrains [4]);'你在這裏忘記了什麼嗎? – johnchen902 2013-05-11 11:43:21