我正在为一个叫做“琐事”的游戏写一个程序。以下是源码:
Trivia.java
public class Trivia implements Serializable {
private String question;
private String answer;
private int points;
public Trivia() {
question = " ";
answer = " ";
points = 0;
}
public String getQuestion() {
return question;
}
public String getAnswer() {
return answer;
}
public int getPoints() {
return points;
}
public void setQuestion(String q) {
question = q;
}
public void setAnswer(String a) {
answer = a;
}
public void setPoints(int p) {
points = p;
}
}Driver.java
public class Driver {
public static void main(String[] args) {
Trivia[] t = new Trivia[5];
for (int i = 0; i < 5; i++) {
t[i] = new Trivia();
}
t[0].setQuestion("How many states are in the US?");
t[0].setAnswer("50");
t[0].setPoints(1);
t[1].setQuestion("Who is the richest person in the US");
t[1].setAnswer("You");
t[1].setPoints(1);
t[2].setQuestion("How many senators come from each state?");
t[2].setAnswer("2");
t[2].setPoints(2);
t[3].setQuestion("What is the largest state?");
t[3].setAnswer("Alaska");
t[3].setPoints(2);
t[4].setQuestion("Who was the thrid president?");
t[4].setAnswer("Thomas Jefferson");
t[4].setPoints(3);
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream("C:\\Work\\workspace\\aman\\src\\trivia\\trivia.dat"));
} catch (IOException e) {
System.out.println("Could not open file");
System.exit(0);
}
try {
outputStream.writeObject(t);
outputStream.close();
} catch (IOException e) {
System.out.println("Writing error");
System.exit(0);
}
ArrayList<Trivia> triviaQuestions = new ArrayList<Trivia>();
try {
ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("C:\\Work\\workspace\\aman\\src\\trivia\\trivia.dat"));
for(int i=0; i<5; i++){ // Repeats the content of the loop five times
triviaQuestions.add((Trivia) inputStream.readObject());
}
inputStream.close(); // Closes the input stream because it is not longer needed
} catch (IOException | ClassNotFoundException e) {
System.out.println("File not found.");
System.exit(0);
}
Trivia yourRandomTrivia = triviaQuestions.get((new Random()).nextInt(triviaQuestions.size())); // This will be your random question
}
// You did not get an auto complete suggestion because you typed outside of a method
}noe当我尝试运行这个程序时,我得到一个错误消息"Ltrivia.Trivia;cannot be cast to trivia.Trivia“。该错误在类驱动程序中的“triviaQuestions.add((Trivia) inputStream.readObject());”行抛出。我对此做了一些研究,发现'L‘表示数据类型的数组。但是,我简单地创建了一个Trivia类型的arrayList,并尝试通过将从inputStream获得的每个元素转换为Trivia类来添加这些元素。有人对此有什么建议吗?
发布于 2016-12-12 14:47:06
您的代码正在编写一个琐碎对象的数组。
然后尝试读取并将其添加到琐碎对象的列表中。
您不能将琐事数组添加到琐事列表中!
这就是消息告诉您的:您不能将类型Trivia[]强制转换为Trivia。因为X的数组与单个X不同。
一种解决方案是:您可以简单地迭代t并写入数组的成员,而不是将t作为一个整体来编写。当然,这意味着您必须以某种方式记住您向该流中写入了多少元素。您可以通过首先编写一个Integer对象来实现,该对象表示随后的Trivia对象的数量。
另一种解决方案是:只需读回Trivia[];然后迭代它;逐个添加各种琐事对象。
编辑:在你的评论上:当你从ObjectInputStream中读取时,你会得到之前放入文件/流中的那些内容。如上所述:您的代码将Trivia类型的数组的单个对象放入字节中...然后你想把这个东西作为一个单独的琐事对象读回来!这不管用!
https://stackoverflow.com/questions/41095433
复制相似问题