我正在为一款名为“ Trivia”的游戏编写程序。下面是源代码:
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;
}
}
驱动程序
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
}
否,当我尝试运行该程序时,出现错误消息“ Ltrivia.Trivia;无法转换为trivia.Trivia”。在类驱动程序“ triviaQuestions.add((Trivia)inputStream.readObject());”行上引发错误。我对此进行了一些研究,发现“ L”表示数据类型的数组。但是,我已经简单地创建了Trivia类型的arrayList,并尝试通过将它们从inputStream中获得的每个元素强制转换为Trivia类来添加它们。
有人对此有任何建议吗?
最佳答案
您的代码正在编写Trivia对象数组。
然后,您尝试读取该内容并将其添加到Trivia对象列表中。
您不能将Trivia数组添加到Trivia列表中!
这就是该消息告诉您的内容:您不能将Trivia []类型转换为Trivia。因为X的数组与单个X不同。
一种解决方案:您可以简单地迭代t并写入数组的成员,而不必整体编写t。当然,这意味着您必须以某种方式记住您在该流中写入了多少个元素。您可以通过首先编写一个整数对象来表示,该整数表示将跟随的Trivia对象的数量。
另一种解决方案:只需读回Trivia [];然后进行迭代;一一添加各种Trivia对象。
编辑:关于您的评论:当您从ObjectInputStream读取内容时,您会得到之前放入文件/流中的内容。就像说的那样:您的代码将Trivia的ARRAY类型的单个对象放入字节中……然后您想将其作为单个Trivia对象读回!那行不通!