This JFrame opens and puts in the empty questions and answers when it starts as it should, but it doesn't print the questionList.size() at line 191. The next button also won't go to the next question which should be retrieved from the text file. I'm not sure if the questionList Vector is being populated by the text file, that's why I put in the questionList.size() line in the first place at line 191. I know I have multiple problems, but I can't figure out where I'm going wrong and my teacher hasn't been able to either. When I step through with the debugger it steps past 191 without printing to screen and steps into 192 and I don't know where it hangs. Any help you can give me would be appreciated. I have the *.txt files in the same folder as my class files.
import java.awt.*;
import java.util.Vector;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class Test extends JFrame implements ActionListener {
public static final int WIDTH = 640;
public static final int HEIGHT = 500;
JPanel upper;
JPanel middle;
JPanel lower;
JTextArea questionArea;
JTextArea choicesArea[];
JTextArea choiceFields[];
JTextArea outputArea;
JButton choiceButtons[];
JButton nextButton;
final String[] typeOfTestPath = { "java.txt", "algebra.txt", "physics.txt" };
final String[] typeOfTestList = { "Java", "Algebra", "Physics" };
JComboBox typeOfTestBox;
final int NUM_OF_BUTTONS = 4;
String buttonLabels[] = { "A", "B", "C", "D" };
int typeOfTest;
// Multiple choice variables
int numCurrentQuestion;
int numQuestions;
int score;
int maxScore;
boolean questionAnswered;
String testChoice;
// parser variables
Question q;
Answer a;
int value;
int mode;
final int GLOBAL_MODE = 0;
final int QUESTION_MODE = 1;
final int ANSWER_MODE = 2;
Vector<Question> questionList;
Vector<String> fileDescriptions;
Vector<String> fileNames;
public Test() {
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
int i;
getContentPane().setLayout(new BorderLayout());
getContentPane().add(upper = new JPanel(), BorderLayout.NORTH);
getContentPane().add(middle = new JPanel(), BorderLayout.CENTER);
upper.setLayout(new GridBagLayout());
upper.setLayout(new GridBagLayout());
upper.setBackground(Color.black);
middle.setBackground(Color.black);
// Top of JFrame
// getFiles();
addComponent(upper, new JLabel("Select category: "), 0, 0);
typeOfTestBox = new JComboBox();
for (i = 0; i < typeOfTestList.length; i++) {
typeOfTestBox.addItem(typeOfTestList[i]);
}
addComponent(upper, typeOfTestBox, 0, 1);
addComponent(upper, questionArea = new JTextArea(4, 50), 1, 0, 3, 3);
typeOfTestBox.setBackground(Color.yellow);
questionArea.setBackground(Color.black);
questionArea.setLineWrap(true);
questionArea.setWrapStyleWord(true);
questionArea.setEditable(false);
questionArea.setForeground(Color.yellow);
// Middle of JFrame
Color color = Color.yellow;
choiceButtons = new JButton[NUM_OF_BUTTONS];
choiceFields = new JTextArea[NUM_OF_BUTTONS];
for (i = 0; i < NUM_OF_BUTTONS; i++) {
addComponent(middle,
choiceButtons[i] = new JButton(buttonLabels[i]), i, 0);
addComponent(middle, choiceFields[i] = new JTextArea(2, 50), i, 1,
2, 1);
choiceFields[i].setBackground(color);
choiceFields[i].setLineWrap(true);
choiceFields[i].setWrapStyleWord(true);
choiceFields[i].setEditable(false);
}
// Bottom of JFrame
getContentPane().add(outputArea = new JTextArea(8, 40),
BorderLayout.SOUTH);
getContentPane().add(lower = new JPanel(), BorderLayout.SOUTH);
addComponent(lower, nextButton = new JButton("Next Question >>"), 0, 2);
outputArea.setBackground(Color.black);
outputArea.setForeground(Color.yellow);
outputArea.setLineWrap(true);
outputArea.setWrapStyleWord(true);
outputArea.setEditable(false);
// Set Listeners
for (i = 0; i < NUM_OF_BUTTONS; i++) {
choiceButtons[i].addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int a = 0;
for (int j = 0; j < NUM_OF_BUTTONS; j++)
if (e.getSource() == choiceButtons[j])
a = j;
Question currentQuestion = getCurrentQuestion();
int correctAnswerNum = currentQuestion.getCorrectAnswer();
Answer answer = currentQuestion.getAnswer(a);
if (answer.isEmpty())
return;
output("Answer " + choiceButtons[a].getText() + " is "
+ answer.getQuestionResult() + ".");
if (answer.hasComment())
output(answer.getComment());
// if answer is correct
if (currentQuestion.hasComment()
&& answer.getValue() == Answer.CORRECT) {
output(currentQuestion.getComment());
}
if (questionAnswered) {
return;
}
questionAnswered = true;
// if answer is not correct
if (answer.getValue() != Answer.CORRECT)
output("The correct answer was "
+ choiceButtons[correctAnswerNum].getText()
+ ".");
int currentScore = currentQuestion.getScore(answer);
score += currentScore;
maxScore += currentQuestion.getMaxScore();
output("You added " + currentQuestion.getScore(answer)
+ " to your score, which is now " + score
+ " out of " + maxScore + ".");
}
});
}
nextButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (!questionAnswered) {
maxScore += getCurrentQuestion().getMaxScore();
questionAnswered = true;
}
if (numCurrentQuestion >= getNumQuestions() - 1) {
clearOutput();
output("No more questions. Please select another test.");
output("Your final score was " + score + " out of "
+ maxScore + " .");
if (score == maxScore)
output("Congratulations, you have a perfect score!");
return;
}
numCurrentQuestion++;
questionAnswered = false;
displayQuestion();
clearOutput();
}
});
typeOfTestBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int j = typeOfTestBox.getSelectedIndex();
String fileName = typeOfTestPath[j];
if (typeOfTestPath[j].length() == 0 && j > 0) {
return;
}
getQuestions(fileName);
output("Question list size is: " + questionList.size());
displayQuestion();
}
});
}// end invoke test
private void addComponent(JPanel p, Component c, int row, int column,
int width, int height) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = column;
gbc.gridy = row;
gbc.gridheight = height;
gbc.gridwidth = width;
p.add(c, gbc);
}
private void addComponent(JPanel p, Component c, int row, int column) {
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = column;
gbc.gridy = row;
p.add(c, gbc);
}
int getNumQuestions() {
return questionList.size();
}
String content(String line) { // returns string after the .
int i = line.indexOf('.');
return line.substring(i + 1).trim();
}
void clearOutput() {
if (this.outputArea == null)
return;
this.outputArea.setText("");
}
void output(String s) {
this.outputArea.append(s + "\n");
}
void displayQuestion() {
Question q = getCurrentQuestion();
questionArea.setText("Question " + (numCurrentQuestion + 1) + " of "
+ getNumQuestions() + "." + q.getMaxScore() + " points "
+ q.getText());
for (int i = 0; i < NUM_OF_BUTTONS; i++)
choiceFields[i].setText(q.getAnswerText(i));
}
void getQuestions(String typeOfTest) {
// initializeTest();
if (typeOfTest.length() == 0)
return;
clearOutput();
Vector<Question> vector = new Vector<Question>();
questionList = vector;
q = new Question();
a = new Answer();
value = Question.DEFAULT_VALUE;
mode = GLOBAL_MODE;
try {
FileInputStream fileStream = new FileInputStream(typeOfTest);
DataInputStream in = new DataInputStream(fileStream);
BufferedReader data = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = data.readLine()) != null) {
parse(line.trim());
}
data.close();
}
catch (FileNotFoundException e) {
output("File not found " + e.getMessage());
}
catch (IOException e) {
output("IO Error while loading questions: " + e.getMessage());
}
}
Question getCurrentQuestion() {
if (numCurrentQuestion >= questionList.size() || numCurrentQuestion < 0) {
return new Question();
} else {
return questionList.get(numCurrentQuestion);
}
}
public static void main(String[] args) {
Test gui = new Test();
gui.setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
void initializeTest() {
numCurrentQuestion = -1;
score = 0;
maxScore = 0;
questionAnswered = false;
}
public void parse(String line) {
if (line.length() == 0)
return;
if (line.startsWith("Question.") || line.startsWith("Q.")) {
q = new Question(content(line), value);
questionList.add(q);
mode = QUESTION_MODE;
return;
}
if (line.startsWith("Comment.") || line.startsWith("C.")
|| line.startsWith("Remark") || line.startsWith("R")) {
switch (mode) {
case GLOBAL_MODE:
output(content(line));
return;
case QUESTION_MODE:
q.appendComment(content(line));
return;
case ANSWER_MODE:
a.appendComment(content(line));
return;
}
return;
}
if (line.startsWith("//")) {
return;
}
if (line.startsWith("Answer.") || line.startsWith("A.")
|| line.startsWith("Incorrect Answer.")
|| line.startsWith("I.")) {
a = new Answer(content(line));
q.addAnswer(a);
mode = ANSWER_MODE;
return;
}
if (line.startsWith("Correct Answer.")) {
a = new Answer(content(line), Answer.CORRECT);
q.addAnswer(a);
mode = ANSWER_MODE;
return;
}
}
}
/******************The Question class************************/
import java.util.Vector;
public class Question {
String text;
String comment;
Vector<Answer> answers;
int value;
public static final int DEFAULT_VALUE = 10;
public static final String NO_QUESTION = "(No question)";
public Question() {
this(NO_QUESTION, new String(), 0);
}
public Question(String text) {
this(text, new String(), Question.DEFAULT_VALUE);
}
public Question(String text, int value) {
this(text, new String(), value);
}
public Question(String text, String comment, int value) {
this.text = text;
this.comment = comment;
this.value = value;
answers = new Vector<Answer>();
}
public void setText(String text) {
this.text = text;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setValue(int value) {
this.value = value;
}
public void addAnswer(Answer answer) {
answers.add(answer);
}
public void appendComment(String append) {
if (comment.length() == 0) {
comment = append;
} else {
comment += "\n" + append;
}
}
public String getText() {
return text;
}
public String getComment() {
return comment;
}
public int getValue() {
return value;
}
public int getMaxScore() {
return value;
}
public int getScore(Answer answer) {
return getMaxScore() * answer.getValue() / answer.MAX_VALUE;
}
public String getAnswerText(int i) {
return getAnswer(i).getText();
}
public Answer getAnswer(int i) {
if (i < getNumAnswers()) {
return answers.get(i);
} else {
return new Answer();
}
}
public int getNumAnswers() {
return answers.size();
}
public int getCorrectAnswer() {
for (int i = 0; i < getNumAnswers(); i++)
if (getAnswer(i).getType() == Answer.CORRECT)
return i;
return 0;
}
public boolean isEmpty() {
return text.equals(NO_QUESTION);
}
public boolean hasComment() {
return (comment.length() > 0);
}
}
/**************The Answer class*********************************/
public class Answer {
String text;
String comment;
int value;
int type;
public static final int INCORRECT = 0;
public static final int PARTIALLY_CORRECT = 5;
public static final int CORRECT = 10;
public static final int MAX_VALUE = 10;
public static final String NO_ANSWER = "(No Answer)";
public Answer() {
this(NO_ANSWER, new String(), Answer.INCORRECT);
}
public Answer(String text) {
this(text, new String(), Answer.INCORRECT);
}
public Answer(String text, String comment) {
this(text, comment, Answer.INCORRECT);
}
public Answer(String text, int type) {
this(text, new String(), type);
}
public Answer(String text, String comment, int type) {
this.text = text;
this.comment = comment;
this.type = type;
this.value = type;
}
public void setText(String text) {
this.text = text;
}
public void setComment(String comment) {
this.comment = comment;
}
public void setValue(int value) {
this.value = value;
}
public void setType(int type) {
this.type = type;
}
public void appendComment(String append) {
if (comment.length() == 0) {
comment = append;
} else {
comment += "\n" + append;
}
}
public boolean hasComment() {
return (comment.length() > 0);
}
public String getText() {
return text;
}
public String getComment() {
return comment;
}
public int getValue() {
return value;
}
public int getType() {
return type;
}
public boolean isEmpty() {
return text.matches(NO_ANSWER);
}
public String getQuestionResult() {
switch (type) {
case INCORRECT:
return "Incorrect";
case CORRECT:
return "Correct";
default:
return "Not classifiable";
}
}
}
/**************Sample text files for testing*******************/
/***************java.txt******************************/
Comment. Java
Comment. This quiz is to test your knowleged of Java.
Question. Which of the following is True?
Correct Answer. A class always has a constructor (possibly automatically supplied by the java compiler).
Answer. In java, an instance field declared public generates a compilation error.
Answer. int is the name of a class available in the package java.lang.
Answer. Instance variable names may only contain letters and digits.
Question. What is true about a constructor?
Answer. must have the same name as the class it is declared within.
Answer. is used to create objects.
Answer. may be declared private
Answer. A and B
Correct Answer. A, B and C
/****************************algebra.txt (the same as Java since I'm just testing so far)************/
Comment. Java
Comment. This quiz is to test your knowleged of Java.
Question. Which of the following is True?
Correct Answer. A class always has a constructor (possibly automatically supplied by the java compiler).
Answer. In java, an instance field declared public generates a compilation error.
Answer. int is the name of a class available in the package java.lang.
Answer. Instance variable names may only contain letters and digits.
Question. What is true about a constructor?
Answer. must have the same name as the class it is declared within.
Answer. is used to create objects.
Answer. may be declared private
Answer. A and B
Correct Answer. A, B and C
/*****************************physics.txt (also the same as java so far)************/
Comment. Java
Comment. This quiz is to test your knowleged of Java.
Question. Which of the following is True?
Correct Answer. A class always has a constructor (possibly automatically supplied by the java compiler).
Answer. In java, an instance field declared public generates a compilation error.
Answer. int is the name of a class available in the package java.lang.
Answer. Instance variable names may only contain letters and digits.
Question. What is true about a constructor?
Answer. must have the same name as the class it is declared within.
Answer. is used to create objects.
Answer. may be declared private
Answer. A and B
Correct Answer. A, B and C