有两个级别的玩家和游戏。实现序列化和文件。序列化工作正常。无法获得对象数组的最大长度。我想要数组中没有对象。
class player {
private String username;
}
class game {
player array[] = new player[100];
int arraysize;
player player;
public void setArraySize(int arraySize) {
this.arraySize = arraySize;
}
public void readdata() { // reading from file starts
//ObjectInputStream input = null;
try {
ObjectInputStream input = new ObjectInputStream(new FileInputStream("myfile.txt"));
array = (NimPlayer[]) input.readObject();
} catch (Exception e) {
e.printStackTrace();
}
initializearraylength(array);
}// reading file ends
public void initializearraylength(NimPlayer[] temparray) {
int size = temparray.length;
setArraySize(size);
System.out.println(size); // output displays size 100
}
}
public display() {
for (int i = 0; i < arraysize; i++) {
System.out.println(array[i].getusername());
}
}
变量arraySize没有初始化。我尝试了这段代码并在try的readdata()firstline中得到一个空指针异常。
java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
at java.io.ObjectInputStream.<init>(Unknown Source)
at game.readdata(game.java:507)
答案 0 :(得分:1)
你的档案是空的。
我不知道为什么你甚至有一个arraySize
变量,如果它始终与array.length.
相同,只需删除它即可。如果你保留它,你肯定不需要两种方法来设置它。
答案 1 :(得分:0)
对象数量
List<NimPlayer> tmp = Arrays.asList((NimPlayer[]) input.readObject());
System.out.println(tmp.size());
对于错误,将声明的变量int arraysize更改为arraySize