我正在使用文件中的信息创建一个问答游戏。一个文本文件将包含所有问题、答案和正确答案。文本文件的结构如下:
Question
answer 1
answer 2
answer 3
answer 4
The right answer repeated
使用从文件中读取的信息,我正在创建一个多重测验。我将所有问题保存在一个数组中,将答案保存在另一个数组中,并将正确答案(重复)保存在另一个数组中。有什么方法可以使用扫描仪,我可以转到文件中的某一行?
这就是我到目前为止所拥有的。我能够从文件中获取所有问题,但我不知道如何阅读答案(我省略了获取文件名的方法和计算行数的方法的代码,因为我知道那些工作):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
//for the file, it is assumed that it is structured as follows: question /n, answer 1 /n, answer 2 /n,
//answer 3 /n, answer 4 /n, correct answer repeated
public class CoreCode {
public static void main(String[] args) {
// TODO Auto-generated method stub
String fileName = getFile();
// gets the file and deals with exceptions
Scanner fileIn = null;
try {
fileIn = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error. File not found.");
// e.printStackTrace();
}
//counts number of lines in the program
int numberOfLines = countLines(fileIn);
//Every sixth line is a question
int numberOfQuestions = numberOfLines / 6;
fileIn.close();
fileIn = null;
try {
fileIn = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
System.out.println("Error. File not found.");
}
//create an array of the questions from the file
String[] questions = getQuestions(fileIn, numberOfQuestions);
fileIn.close();
for (int i = 0; i < questions.length; i++){
System.out.println(questions[i]);
}
}
// method to get file name
public static String getFile() {
}
//method to count total lines in file
public static int countLines(Scanner fileIn) {
}
// method to read questions
public static String[] getQuestions(Scanner fileIn, int numberOfQuestions) {
String[] questions = new String[numberOfQuestions];
int count = 0;
//method 2, every sixth line is a question
while (fileIn.hasNext()){
String line = fileIn.nextLine();
if (count == 0 || count % 6 == 0){
//count is number of total lines, so the index is count divided by 6 (every sixth lines is
//a question
int index = count / 6;
questions[index] = line;
}
count++;
}
return questions;
}
}