Randomizing text file read in Java

前端 未结 4 2090
春和景丽
春和景丽 2021-01-18 11:32

I am trying to read a text file in Java, basically a set of questions. With four choices and one answer. The structure looks like this:

question

o

4条回答
  •  忘掉有多难
    2021-01-18 12:26

    Create a class to hold a question and read the file into an array of these objects.

    Break the problem into three steps. The first step is to read in the data file and store all of the data in objects. The second step is to randomize the order of those objects. The final step is to print them out.

    ArrayList questions = new ArrayList();
    for(ar=0;ar<2;ar++){
      q=br.readLine();
      a=br.readLine();
      b=br.readLine();
      c=br.readLine();
      d=br.readLine();
      String tempo=br.readLine();
      ans=tempo.charAt(0);
    
      questions.add(new Question(q, a, b, c, d, ans));
    }
    

    Randomize the array like this:

    Collections.shuffle(questions);
    

    Then just loop through the questions and output them.

    for (Question q: questions) {
      q.write();
      System.out.println(); // space between questions
    }
    

    Create a question class like this to hold your data:

    public class Question {
      private String question;
      private String option1;
      private String option2;
      private String option3;
      private String option4;
      private String answer;
    
      public Question(String question, String option1, String option2, String option3,
                      String option4, String answer) {
        this.question = question;
        this.option1 = option1;
        this.option2 = option2;
        this.option3 = option3;
        this.option4 = option4;
        this.answer = answer;
      }
    
      public void write() {
        System.out.println(this.question);
        System.out.println(this.option1);
        System.out.println(this.option2);
        System.out.println(this.option3);
        System.out.println(this.option4);
        System.out.println("Answer: "+this.answer);
      }
    }
    

提交回复
热议问题