我正在研究一個將成爲瑣事遊戲的項目。我需要創建一個循環遍歷文本文件並創建一個對象然後將其添加到ArrayList的方法。該文件的每7行都是一個新對象。對象本身是一個包含的東西,如可能的答案等問題如何循環Java中的文本文件,將7行對象添加到對象數組中?
我的對象構造:
Which of the following is not a programming language?
4
Python
Java
PHP
SQL
4
:
public Question(String question, int possibleAnswers, String[] answers, int correctAnswer) {
this.question = question;
this.possibleAnswers = possibleAnswers;
this.answers = answers;
this.correctAnswer = correctAnswer;
}
我通過有像這樣的問題信息文件需要循環
我很困惑我應該如何產生每個對象,而循環通過這是就我已經得到的方法:
public static ArrayList<Object> createQuestions(String filename) throws IOException {
ArrayList<Question> questionObj = new ArrayList<Question>();
Question questionArray[] = null;
Scanner fileReader = new Scanner(new File(filename));
while (fileReader.hasNext()) {
for (int i = 0; i <= 10; i++) {
questionArray[i] = new Question();
}
}
fileReader.close();
爲什麼不把對象存儲爲XML或JSON?很多庫支持序列化/反序列化。 – mre
它正在處理的任務,所以它必須來自.txt文件 –
明白了,謝謝。 – mre