繁体   English   中英

读取具有不同行的文件并存储到变量中

[英]Reading file with different lines and storing into variables

我有一些关于读取不同行的文件输入的问题。 例如,我正在尝试读取类似于测试的文件。 文件的第一行将具有测试的名称。 第二行有问题。 第三行包含两个整数,第一个负责选择题中的选项数量,第二个是正确选项。 最后,接下来的“x”行是潜在的选择。

测试文件

单元考试 3
“野马最好的颜色是什么?”
4,1
红色的
蓝色的
黑色的
白色的
“野马是哪一年发明的?”
3,3
1978年
2015
1964年
等等等等

 Scanner scnr = new Scanner(new FileInputStream("test.txt"));
    String line;
    while (scnr.hasNextLine()) {
        line = scnr.nextLine();
        String[] data = line.split(",");
String testTitle = data[0];

...这是我的问题所在,因为下一行现在不是测试标题,但是,该行的位置仍然是 data[0] 。

此外,问题继续到下一部分,因为现在我正在处理 integer 行。 我知道它看起来像:

int numOptions = Integer.parseInt(data[0]);
int correct = Integer.parseInt(data[1]);

但这会导致编码出现大量错误。 知道怎么做吗?

最后请注意,并非所有问题都有相同数量的潜在选项。 例如,与我的示例测试中的第一个问题有 4 个问题相比,如果有一个只有 2 个选项的问题是对或错,这将如何变化?

如果输入的结构是正确的你要扫描问题,然后是答案数据。 您检查数字并获得下 x 行作为答案的数据。

示例 function:

void func(Scanner s) {
    String question = s.nextLine();
    String[] data = s.nextLine().split(",");
    String[] answers = new String[Integer.parseInt(data[0])];
    for (int i = 0; i < answers.length; i++) {
        answers[i] = s.nextLine();
    }
    int correct = Integer.parseInt(data[1]);
}

我建议使用 function 和 object 返回,但你可以把它放在你的循环中。

跟踪您在测验文件中的位置可能在某种程度上是有益的,但特别关键的是在创建测验文件时在整个测验文件中保持相同的数据结构。

我认为通常情况下,您会想要显示测验标题。 在您的示例中,这是文件的第一行。 但是,如果您想在测验文件中添加评论,或者第一行不是测验标题怎么办。 应在数据中提供一些内容以将标题与其他数据区分开来,例如:

UnitExam3.txt 文件:

# This test is about various Cars.
# Each correct answer applies as a single point.
# This test will be applied to Student's overall grade value.

Title: Unit Exam 3

"What is the best color for a Mustang?"
4,1
Red
Blue
Black
White

"What year was the Mustang invented?"
3,3
1978
2015
1964

如您所见,此测验文件易于阅读和使用。 您还可以看到测验标题(单元考试 3)以名为Title:的属性为前缀。 这无疑将标题与测验文件中的任何其他内容区分开来,因此很容易检索。

各个测验问题在测验文件中很容易区分,因为它们用引号(“...”)括起来,这很好,因为每个问题中没有其他任何东西具有此功能。 因此,当检测到一行以引号 ( " ) 开头时,我们知道它是一个新测验问题的开始。

正如您在下面的代码中看到的,测验问题数据是根据需要从测验文件中热读取的。 当获得单个问题数据时,它会立即显示在控制台上,供学生回答。 一旦回答,学生就会被告知所提供的答案是对还是错,并继续阅读下一个测验问题。

// 'Try With Resources' is used here to auto-close the reader (scnr).
try (Scanner scnr = new Scanner(new File("UnitExam3.txt"))) {
    Scanner input = new Scanner(System.in);
    String line;
    String quizName;
    int questionCount = 0;
    int correct = 0;
    int wrong = 0;
    while (scnr.hasNextLine()) {
        line = scnr.nextLine().trim();
        // Skip any comment or blank lines (comment lines start withe a: #)
        if (line.equals("") || line.startsWith("#")) {
            continue;
        }
        // Is this line the title?
        if (line.toLowerCase().startsWith("title:")) {
            // Yes it is...
            quizName = line.substring(6).trim();
            // Display the Test Name To Console...
            System.out.println(quizName);
            // Underline it taking advantage of the String.join() 
            // and the Collection.nCopies() methods...
            System.out.println(String.join("", Collections.nCopies(quizName.length(), "=")));
        }
        // Is this line the start of a Quiz Question?
        else if (line.startsWith("\"")) {
            // Yes it is...
            questionCount++;    // increment question count
            // Remove quotes from question.
            String question = line.substring(1, line.length() - 1);
            // Get the rest of data for this particular question...
            // Get the Number of Choices and Answer line
            String questInfoLine = scnr.nextLine().trim();
            int numberofChoices = Integer.parseInt(questInfoLine.split("\\s{0,},\\s{0,}")[0]);
            String answerChoice = questInfoLine.split("\\s{0,},\\s{0,}")[1];
            // Get the multiple choice answers
            String[] choices = new String[numberofChoices];
            for (int i = 0; i < numberofChoices; i++) {
                choices[i] = scnr.nextLine().trim();
            }
            // Display the test question to Console...
            System.out.println();
            System.out.println("Question #" + questionCount + ":");
            System.out.println(question);
            for (int i = 0; i < choices.length; i++) {
                System.out.println((i + 1) + ") " + choices[i]);
            }
            System.out.print("Answer: --> ");
            // Wait for answer from Student...
            String answer = input.nextLine();
            // Check Answer...
            if (answer.equals(answerChoice)) {
                System.out.println("Correct");
                correct++;  // increment correct answer count
            }
            else {
                System.out.println("Wrong!");
                wrong++;    // increment wrong answer count
            }
        }
        // Continue reading in Quiz File Questions until end of file (EOF).
    }

    // Display Student results from the Quiz(add averaging etc if you like).
    System.out.println();
    System.out.println("========== Results ===========");
    System.out.println("Answers Correct: " + correct);
    System.out.println("Answers Wrong: " + wrong);
    System.out.println("==============================");
}
catch (FileNotFoundException ex) {
    System.err.println(ex);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM