0

我正在使用文件中的信息创建一个问答游戏。一个文本文件将包含所有问题、答案和正确答案。文本文件的结构如下:

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;
}

}
4

2 回答 2

0

我会按照另一个答案BufferedReader中的建议阅读文件,并将信息保存在一个包含以下内容的对象中:

class Question {
    String question;
    String[] answers;
    String correctAnswer;
}

然后在您阅读文件后,您将在内存中拥有所有问题和答案(存储在 中ArrayList)。这样你就只会读一次文件。

于 2013-11-12T18:12:57.280 回答
0
 LineIterator it = IOUtils.lineIterator(
       new BufferedReader(new FileReader("file.txt")));
 for (int lineNumber = 0; it.hasNext(); lineNumber++) {
    String line = (String) it.next();
    if (lineNumber == expectedLineNumber) {
        return line;
    }
 }

由于缓冲区,这将稍微更有效。

看一眼Scanner.skip(..)

于 2013-11-12T17:56:53.710 回答