用Java编写一个题库管理系统,要求录入题目功能中的题目录入一道采用文件的形式保存,界面在控制台输出,写出源码
时间: 2024-03-06 09:48:42 浏览: 70
好的,下面是一个简单的Java题库管理系统的源码,包括题目类Question和题库管理类QuestionManager:
Question类:
```java
public class Question {
private String content; // 题目内容
private String[] options; // 选项
private int answer; // 答案
public Question(String content, String[] options, int answer) {
this.content = content;
this.options = options;
this.answer = answer;
}
public String getContent() {
return content;
}
public String[] getOptions() {
return options;
}
public int getAnswer() {
return answer;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(content).append("\n");
for (int i = 0; i < options.length; i++) {
sb.append((char)('A' + i)).append(". ").append(options[i]).append("\n");
}
sb.append("Answer: ").append((char)('A' + answer));
return sb.toString();
}
}
```
QuestionManager类:
```java
import java.io.*;
public class QuestionManager {
private static final String FILE_NAME = "questions.txt"; // 题目文件名
// 添加题目到文件中
public void addQuestion(Question question) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(FILE_NAME, true))) {
writer.write(question.toString());
writer.newLine();
} catch (IOException e) {
e.printStackTrace();
}
}
// 从文件中读取所有题目
public void printAllQuestions() {
try (BufferedReader reader = new BufferedReader(new FileReader(FILE_NAME))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// 从文件中删除所有题目
public void clearAllQuestions() {
try (PrintWriter writer = new PrintWriter(FILE_NAME)) {
writer.print("");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
```
以上代码实现了添加题目、打印所有题目以及清空所有题目的功能。您可以根据需求进行修改和完善。
阅读全文