0

Could anyone help me rewrite this code using a 2D array to loop through and display the choices?

The following is a quiz-type game. I have a text file with this data that is read by the program, So first the question, then the 4 answer choices, then the answer (I have 20 questions in the file):

1) What is 1+2 = ...?
a) 2
b) 3
c) 0
d) 1
b
...

Here is the code:

import java.io.File;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class GameQuiz
{
    public static void main(String[] args) {
        String[] data = new String[120];
        String question = "";
        int count = 0;
        try{
            Scanner inFile = new Scanner(new File("questions.txt"));
            while (inFile.hasNext()){
                data[count] = inFile.nextLine();
                count++;
            }
            inFile.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        int choice = 0, numCorrect = 0, i = 0;
        char correctAnswer = ' ', correct = ' ';
        String answer= "";
        String answerChoices[] = {"a", "b", "c", "d"};
        for (int j = 0; j < 20; j++)
        {
            answer = "";
            for (i = 0; i < 5; i++)
            {
                answer += data[i+(j*6)] + "\n";
            }
            correctAnswer = data[i+(j*6)].charAt(0);

            choice = JOptionPane.showOptionDialog(null, answer, "Quiz Game",
                    0, 3, null, answerChoices, null);


            if (choice == 0) correct = 'a';
            if (choice == 1) correct = 'b';
            if (choice == 2) correct = 'c';
            if (choice == 3) correct = 'd';

            if (correct == correctAnswer)
            {
                numCorrect ++;
                JOptionPane.showMessageDialog(null, "Correct!");
            }
            else JOptionPane.showMessageDialog(null, "Sorry.\n"+
                    "The correct answer was "+correctAnswer);
        }
        JOptionPane.showMessageDialog(null, "You have "+numCorrect+"/20 correct answers.");
    }
}
NotToBrag
  • 655
  • 1
  • 16
  • 36
  • Do you really want a 2D Array or is that the idea you currently have? I would create a class with the question and an answer array and then store an object for each question in an ArrayList. – Chris Apr 28 '15 at 12:37

1 Answers1

0

You don't need to change too much:

    while (inFile.hasNext()){
         for(int i = 0; i <20; i++){
              for(int j = 0;j <6; j++){
                   data[i][j] = inFile.nextLine();
                   count++;
              }
         }
    }

and:

    for (i = 0; i < 5; i++){
          answer += data[j][i] + "\n";
    }
    correctAnswer = data[j][i].charAt(0);

it should work fine. However, you should think about better solution, as suggested in comments. This is not most efficient way.

EDIT: Also you need to change data[] declaration on:

String[][] data = new String[20][6];
m.cekiera
  • 5,365
  • 5
  • 21
  • 35