A.R Hatim
A.R Hatim

Reputation: 27

Storing many Strings in a two-dimensional String array

I'm trying to make a quiz program in java using netbeans for a school project. I have about 40 questions and need to store them in a two dimensional array.
String qna[][]=new String[40][5];\\ for the question and each of the four options which will be displayed on 4 toggle buttons
My problem is that i have to type a large amount of code to load each question and its' four options and it's hard when I have to edit questons.
Is there a more efficient way to do this(Such as using a text document or something stored elsewhere)?

Upvotes: 0

Views: 94

Answers (3)

André Ramos
André Ramos

Reputation: 44

How about creating a class Question that stores a question and all it's answers?

class Question {

private String question;

private List<String> answers;

Question(String question) {
    this.question=question;
    answers = new ArrayList<>();
}

public void addAnswer(String answer){
    this.answers.add(answer);
}
//Getters
}

Then you could create a class that reads from a text file and creates a List for all your questions using a BufferedReader like this:

public class QuestionLoader {

//Pass the path to your file as the parameter
public List<Question> loadFromFile(String path) {
    List<Question> allquestions = new ArrayList<>();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(new File(path)));
        Question question = null;
        String line = br.readLine();
        while (line != null) {
            if (line.startsWith("Q::")) {

                question = new Question(line.split("::")[1]);
            } else if (line.startsWith("A::")) {
                question.addAnswer(line.split("::")[1]);
            } else if (line.equals("")) {
                allquestions.add(question);
            }
            line = br.readLine();
        }
        br.close();
    } catch (FileNotFoundException ex) {
        Logger.getLogger(QuestionLoader.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(QuestionLoader.class.getName()).log(Level.SEVERE, null, ex);
    }
    return allquestions;
}

}

It reads from a file structured as

Q::What is the meaning of life?
A::42
A::33 
A::pi
A::all of the above

Q::What?
A::Nothing 
A::Something

Simply separate questions from each other by a new line. In this way you would not need to change your code should you need an arbitrary number of questions or answers. It may not be the most efficient but I find it more pleasant to work with lists than with arrays.

Upvotes: 0

Sweeper
Sweeper

Reputation: 271175

You should not use a 2D array to store questions and answers, it's bad and fragile!

You can make a class called CompoundQuestion which contains the question and answers and then create some objects of CompoundQuestion. The class should be something like this:

public class CompoundQuestion {
    private String question;
    private String[] answers;

    public String getQuestion () { return question; }

    public String[] getAnswers () { return answers; }

    public CompoundQuestion (String question, String[] answers) {
        this.question = question;
        this.answers = answers;
    }

    public CompoundQuestion (String question, String... answers) {
        this(question, answers);
    }
}

The above is just a simple implementation. If you don't understand the concept of classes, read this:

https://docs.oracle.com/javase/tutorial/java/javaOO/classes.html

If you don't know what the String... thing is doing, read this:

https://docs.oracle.com/javase/1.5.0/docs/guide/language/varargs.html

If you still don't understand, just use the first overload of the constructor.

And you can use your class like this (Assuming you understood the String... part):

CompoundQuestion myQuestion = new CompoundQuestion ("Is Sweeper handsome?", "Yes!", "YASSS", "Yeeeeeeeesssss");

And then you can store this in an array:

CompoundQuestion[] questionArray = new CompoundQuestion[40];

Of course, you can get your questions' text and the answers by calling:

getQuestion ()

and

getAnswers ()

If you don't understand classes, just use a 2D array... I am speechless.

Just in case you also want to store the correct answer, you can add some code to the CompoundQuestion class:

private int correctAnswer;
public String getCorrectAnswer () {
    return answers[correctAnswer];
}

And you can add that to the constructor as well!


EDIT:

You can also put the CompoundQuestion in a text file so that you can save it even after your program has finished!

Use ObjectInputStream and ObjectOutputStream. The latter to "serialize" the CompoundQuestion in a file on your computer! And use the former to deserialize it back to a CompoundQuestion object.

More information here:

ObjectInputStream: http://www.tutorialspoint.com/java/io/java_io_objectinputstream.htm

ObjectOutputStream: http://www.tutorialspoint.com/java/io/java_io_objectoutputstream.htm

Upvotes: 2

shanmuga
shanmuga

Reputation: 4499

Instead of using a muti-dimensional arrays create a class QnA to store the questions and corresponding answer options.

class QnA {
     String question;
     String[] answer_options;
}

Store your questions (and corresponding answers) in json (txt) file

[ { "question": "How are you", "answer_options": [ "Bad", "OK", "GOOD" ] }, { "question": "What colour is sky", "answer_options": [ "Blue", "Green", "Red" ] } ]

Using this file populate the and array of QnA objects such as QnA[] Qestions.

There are many libraries to parse json.

Upvotes: 0

Related Questions