write a method to select a file via a JFileChooser and to read all the questions from that file into an array/list of Question objects (assume that file has the structure mentioned above);怎么写
时间: 2024-02-15 19:05:48 浏览: 24
以下是一个示例方法,用于从文件中读取问题并将其存储在Question对象的List中:
```java
public List<Question> readQuestionsFromFile() {
List<Question> questions = new ArrayList<Question>();
JFileChooser chooser = new JFileChooser();
int result = chooser.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = chooser.getSelectedFile();
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String[] parts = line.split(",");
String text = parts[0];
String[] answers = Arrays.copyOfRange(parts, 1, 5);
int correctAnswer = Integer.parseInt(parts[5]);
Question question = new Question(text, answers, correctAnswer);
questions.add(question);
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
return questions;
}
```
这个方法使用JFileChooser来让用户选择文件。然后,它使用Scanner来逐行读取文件,对每一行进行分割,以获取问题文本、答案和正确答案的信息。最后,它使用这些信息创建一个Question对象,并将其添加到Question对象的List中。最后,它返回包含问题的List。
请注意,此示例代码假定文件的格式为:问题文本,答案1,答案2,答案3,答案4,正确答案的编号(1-4之间)。你需要根据你自己的文件格式进行修改。