从文件加载到arraylist

时间:2016-03-26 05:54:19

标签: java arraylist

所以我正在编写一个测验程序,其中包含一些不确定的问题(在Java中),我在完成以下事情时遇到了问题:

1)从文件加载测验问题并存储在arraylist中并访问它(需要帮助!) 2)不接受正确答案 - 给我错误(逻辑错误) 3)并非显示所有答案选择

以下是代码:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;

public class Quiz {

 public void writeFile() {
   Question qn = new Question();
   try {
     PrintWriter out = new PrintWriter("quiz.txt");
     out.println(qn.Question);
     out.println(qn.numberOfChoices);
     qn.answerChoices = new String[qn.numberOfChoices];
     for (int i = 0; i < qn.numberOfChoices; i++) {
         out.println(qn.answerChoices[i]);
     }
     out.println(qn.correctAnswer);
     out.println(qn.numOfTries);
     out.println(qn.numOfCorrectTries);
     out.close();
   } catch (IOException f) {
     System.out.println("Error.");
   }
   qn.getQuestion();
 }

 public void readFile() {
     File file = new File ("quiz.txt");
     boolean exists = file.exists();
     Quiz q = new Quiz();
     Question a = new Question();
     List<String> question = new ArrayList<String>();
     String[] answerChoices = a.answerChoices;
     try {
        if (exists == true) {
            Scanner s = new Scanner(file);
            a.Question = s.nextLine();
            a.numberOfChoices = s.nextInt();
            a.answerChoices = new String[a.numberOfChoices];
            for (int i = 0; i < a.numberOfChoices; i++) {
                a.answerChoices[i] = s.nextLine();
            }
            s.nextLine();
            a.correctAnswer = s.nextInt();
            a.numOfTries = s.nextInt();
            a.numOfCorrectTries = s.nextInt();
            a.getQuestion();
         } else {
            q.writeFile();
         }
     } catch (IOException e) {
       System.out.println("File not found.");
     }
 }

public static void main (String[] args) {
    Scanner in = new Scanner(System.in);
    Quiz qz = new Quiz();
    Question b = new Question();
    int Selection;
    List<String> question = new ArrayList<String>();

    System.out.println("Welcome to the Quiz Program! Good luck!");
    do {
       qz.readFile();
       System.out.println("Your answer?: ");
       Selection = in.nextInt();
       if (Selection == b.correctAnswer) {
          b.numOfCorrectTries++;
          b.getQuestion();
       } else {
          b.getQuestion();
       }
    } while (Selection < b.numberOfChoices);
    while (Selection > b.numberOfChoices || Selection < 0) {
       System.out.println("Error. Try again");
       System.out.println("Your answer?: ");
       Selection = in.nextInt();
    }
  }
}

和问题类:

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;

public class Question {

 int correctAnswer;
 int numOfTries;
 int numOfCorrectTries;
 int numberOfChoices;
 String Question;
 String[] answerChoices;

 public Question() {

 }
 public void getQuestion() {
    System.out.println("Question: " + Question);
    System.out.println("Answer: ");
    for (int i = 0; i < numberOfChoices; i++) {
        System.out.println(answerChoices[i]);
    }
 }

 public double getPercentageRight() {
     double percentageRight = (numOfCorrectTries / numOfTries) * 100;
     percentageRight = Math.round(percentageRight * 100);
     percentageRight = percentageRight / 100;
     return percentageRight;
 }
}  

QUIZ.TXT:

How many licks does it take to get to the tootsie roll center of a  
tootsie pop?
4
one
two
three
four
2
14
5
What is your name?
3
Arthur, King of the Britons
Sir Lancelot the Brave
Sir Robin the Not-Quite-So-Brave-As-Sir Lancelot
0
14
6
Who's on first?
5
What
Why
Because
Who
I don't know
3
14
7
Which of the following is a terror of the fire swamp?
4
Lightning sand
Flame spurt
R.O.U.S.
All of the above
3
14
4
Who is the all-time greatest pilot?
6
Manfred von Richthofen
Chuck Yeager
Hiraku Sulu
Luke Skywalker
Kara Thrace
Charles Lindbergh
4
14
9

2 个答案:

答案 0 :(得分:1)

一些问题:

您的List<String> question = new ArrayList<String>();应该类似于List<Question> questionBank = new ArrayList<Question>();,因为将所有内容保存为字符串(而不是问题对象)会非常麻烦。在阅读代码时,名称questionBank也比question更具描述性。我还建议将questionBank作为类变量,以便在Quiz课程中轻松访问。

您永远不会将问题添加到您的ArrayList中,但我怀疑您已经知道这一点,并且在解决其他问题时它只是低优先级。

你的Question课程也有点不同寻常。构建它的更好方法可能是这样的:

public class Question {

     private int correctAnswer;
     private int numOfTries;
     private int numOfCorrectTries;
     private String question;
     private String[] answerChoices;

     public Question(String question, String[] answerChoices,
             int correctAnswer, int numOfTries, int numOfCorrectTries) {
         this.question = question;
         this.answerChoices = answerChoices;
         this.correctAnswer = correctAnswer;
         this.numOfTries = numOfTries;
         this.numOfCorrectTries = numOfCorrectTries;
     }

     public void getQuestion() {
            System.out.println("Question: " + question);
            System.out.println("Answer: ");
            for (int i = 0; i < answerChoices.length; i++) {
                System.out.println(answerChoices[i]);
            }
     }

     public double getPercentageRight() {
         double percentageRight = (numOfCorrectTries / numOfTries) * 100;
         percentageRight = Math.round(percentageRight * 100);
         percentageRight = percentageRight / 100;
         return percentageRight;
     }

}

我删除了numberOfChoices的变量,因为它与answerChoices.length相同。我还将您的Question重命名为question,因为Java中的变量通常遵循camelCase。我不确定其他方法是什么,或者它们应该如何显示输出,所以我主要是让它们独自存在。

对于读取文件,我认为你可以做一些与你所拥有的类似的东西,但是我会发布符合Question类的新构造函数的代码。

private void addQuestions() {
    File quizText = new File("quiz.txt");
    try {
        Scanner fileIn = new Scanner(quizText);
        while (fileIn.hasNextLine()) {
            String question = fileIn.nextLine();
            int numberOfAnswers = fileIn.nextInt();
            fileIn.nextLine();
            String[] answers = new String[numberOfAnswers];
            for (int i = 0; i < numberOfAnswers; i++) {
                answers[i] = fileIn.nextLine();
            }
            int correctAnswer = fileIn.nextInt();
            int numOfTries = fileIn.nextInt();
            int numOfCorrectTries = fileIn.nextInt();
            fileIn.nextLine();
            Question nextQuestion =
                new Question(question, answers, correctAnswer, numOfTries, numOfCorrectTries);
            questionBank.add(nextQuestion);
        }
        fileIn.close();
    } catch (IOException e){
        e.printStackTrace();
        System.out.println("File Not Found.");
        return;
    }
}

我还将变量设为私有,但您可以为它们创建自定义getter,以防止它们从外部直接访问(和/或更改)。使用此代码,我能够创建一个包含所有五个问题的问题库,并显示正确的答案以及所有可能的选择,因此希望它指向正确的方向。

答案 1 :(得分:0)

我重新上课了。在我的例子中,您回答了上述所有问题。我将逐一解释它们。

public class Quiz {

List<Question> question = new ArrayList<Question>();

public void writeFile() {
    Question qn = new Question();
    try {
        PrintWriter out = new PrintWriter("quiz.txt");
        out.println(qn.Question);
        out.println(qn.numberOfChoices);
        qn.answerChoices = new String[qn.numberOfChoices];
        for (int i = 0; i < qn.numberOfChoices; i++) {
            out.println(qn.answerChoices[i]);
        }
        out.println(qn.correctAnswer);
        out.println(qn.numOfTries);
        out.println(qn.numOfCorrectTries);
        out.close();
    } catch (IOException f) {
        System.out.println("Error.");
    }
    qn.getQuestion();
}

public void readFile() {
    File file = new File("quiz.txt");
    boolean exists = file.exists();
    Quiz q = new Quiz();
    Question a = new Question();
    String[] answerChoices;
    try {
        if (exists == true) {
            Scanner s = new Scanner(file);
            String line = "";
            while (s.hasNextLine()) {
                line = s.nextLine();
                if (line.startsWith("---")) {
                    a = new Question();
                    a.Question = line.substring(4);
                } else if (line.startsWith("choices : ")) {
                    a.numberOfChoices = Integer.parseInt(line.substring(10).trim());
                    a.answerChoices = new String[a.numberOfChoices];
                    for (int i = 0; i < a.numberOfChoices; i++) {
                        a.answerChoices[i] = s.nextLine();
                    }
                } else if (line.startsWith("correct answer : ")) {
                    a.correctAnswer = Integer.parseInt(line.substring(17).trim());

                } else if (line.startsWith("No of Tries : ")) {
                    a.numOfTries = Integer.parseInt(line.substring(14).trim());

                } else if (line.startsWith("No of correct Tries : ")) {
                    a.numOfCorrectTries = Integer.parseInt(line.substring(22).trim());
                    question.add(a);
                }
            }
        } else {
            q.writeFile();
        }
    } catch (IOException e) {
        System.out.println("File not found.");
    }
}

public static void main(String[] args) {
    Quiz qz = new Quiz();
    qz.readFile();
    Question b = new Question();
    int selection;

    //real program starts here
    System.out.println("Welcome to the Quiz Program! Good luck!");
    System.out.println("****************************************");

    b = qz.question.get(2); // you can implement how your questions are taken from list of questions
    b.getQuestion();
    Scanner in = new Scanner(System.in);
    System.out.print("Your answer?: ");
    selection = in.nextInt();

    if (selection == b.correctAnswer) {
        b.numOfCorrectTries++;
        System.out.println("Correct answer");

    } else {
        System.out.println("Incorrect answer");
    }
}

}

1)从文件加载测验问题并存储在arraylist中并访问它(需要帮助!)

而不是使用

 List<String> question = new ArrayList<String>();

使用以下作为类变量。所以你可以在课堂的任何地方访问它们

 List<Question> question = new ArrayList<Question>(); 

2)不接受正确答案 - 给我错误(逻辑错误)

逻辑在主块中得到纠正。

3)并非显示所有答案选项

重新读了readFile()方法。但要想成功使用这个逻辑,你需要重新创建你的quiz.txt,如下所示。

--- How many licks does it take to get to the tootsie roll center of a tootsie pop?
choices : 4
one
two
three
four
correct answer : 2
No of Tries : 14
No of correct Tries : 5
--- What is your name?
choices : 3
Arthur, King of the Britons
Sir Lancelot the Brave
Sir Robin the Not-Quite-So-Brave-As-Sir Lancelot
correct answer : 0
No of Tries : 14
No of correct Tries : 6
--- Who's on first?
choices : 5
What
Why
Because
Who
I don't know
correct answer :  3
No of Tries : 14
No of correct Tries : 7
--- Which of the following is a terror of the fire swamp?
choices : 4
Lightning sand
Flame spurt
R.O.U.S.
All of the above
correct answer : 3
No of Tries : 14
No of correct Tries : 4
--- Who is the all-time greatest pilot?
choices : 6
Manfred von Richthofen
Chuck Yeager
Hiraku Sulu
Luke Skywalker
Kara Thrace
Charles Lindbergh
correct answer : 4
No of Tries : 14
No of correct Tries : 9

注意: 问题的选择基于

   b = qz.question.get(2);

在main()中。要根据随机选择的问题创建问题文件,您可以创建一个单独的方法并从该方法中提示问题。请进一步参考Math.random()。

还可以为这种应用程序创建XML文件而不是txt。 Google for&#34; Java and XML&#34;

希望这有帮助。