0

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)?

7
  • You can just save each question and options in a text file (specially formatted) and read it in from there. Commented Nov 11, 2015 at 4:58
  • 2
    Why don't you create a class with a question string and 4 options. Then you can create an array of Objects of this class. Commented Nov 11, 2015 at 4:58
  • @3kings how can I do that? Commented Nov 11, 2015 at 4:59
  • So just put them all in a file like maybe comma separated and read them all in. This is the question, the first option, the second option, the third option, the fourth option Then you can read line by line in the file and easily call a .split(",") on the string you read in. Commented Nov 11, 2015 at 5:02
  • @3kings No sorry,I meant How do I read the text file? Commented Nov 11, 2015 at 5:04

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

OP, btw, if you really want a simpler implementation, just declare a bunch of variables in the class. Basically, no getters, no constructors and no encapsulation. This is simpler but a bad practise. Choose wisely!
I added some information on how to store the thing in a file to implement late binding. That way the program doesn't have to initialize all 40 questions using the constructor. It can just read them from a file. However, the file is in binary so don't try to edit that!
0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.