Randomizing text file read in Java

前端 未结 4 2084
春和景丽
春和景丽 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:29

    I think a little structural changes will help a lot and make this much easier for you. Define new classes: Question and Answer. Let Question have the options and Answer inside of it. That's object composition.

    Look into the Collection API. With a Collection of Questions, you can use the shuffle method to randomize them in one line. Let Java do the work for you.

    So you might have:

    Collection questions = new ArrayList();
    
    questions.add(...);
    questions.add(...);
    questions.add(...);
    
    questions.shuffle();
    

    To embellish a little more about why you would want to do it this why... You want to separate your concerns the best you can. Questions, answers, and options are all different concerns. The user's response is a concern. The randomization of the questions is a concern. The response to the user's response is a concern.

    Being a good software developer, you're going to want to compartmentalize all of these things. Java's construct for accomplishing this is the Class. You can develop your ideas relatively independently inside their own class. When you're satisfied with your Classes, all you have to do is connect them. Define their interfaces, how they talk to each other. I like to define the interfaces first, but when I started out, I found it a little easier to worry about that later.

    Might seem like a lot of work, with all of these Classes and interfaces and what not. It'll take a fraction of the time to do it this way when you get good. And your reward is testability reusability.

提交回复
热议问题