我正在编写一个带有问题和答案的简单测验,并希望针对4类问题制作4个ArrayLists。用户应该选择一个类别并从ArrayList中回答10个随机问题。 我找到了一段没有类别的ArrayList代码。我不知道如何实现4个ArrayLists并从一个文本文件中填充它们。有人可以帮帮我吗?
public class Questions {
private ArrayList<Question> questions = new ArrayList<Question>();
public Questions() {
try {
File f = new File("src/main/resources/questions.txt");
FileReader r = new FileReader(f);
BufferedReader reader = new BufferedReader(r);
Scanner scanner = new Scanner(reader);
String line;
String question = "";
String[] alternatives = null;
int answer = 0;
int numberOfAlternatives = 0;
int counter = 0;
do {
do {
line = scanner.nextLine();
if (line.contains("?")) { //stores the question
question = line;
} else if(counter == 0 && line.length() == 1) { //stores the number of alternatives
numberOfAlternatives = Integer.valueOf(line);
alternatives = new String[numberOfAlternatives];
} else if (line.contains(")")) { //stores the alternatives
alternatives[counter++] = line;
} else if (Character.isDigit(line.indexOf(0)) || counter == numberOfAlternatives) { //Stores the answer
answer = Integer.valueOf(line);
}
} while (answer == 0);
questions.add(new Question(question, alternatives, answer));
numberOfAlternatives = 0;
counter = 0;
answer = 0;
} while (scanner.hasNext());
r.close();
reader.close();
scanner.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public ArrayList<Question> getQuestions() {
return questions;
}
}