I have to write a GUI based quiz game in Java, but I have no idea how to use the following code to finish the program. The questions and answers are in a text file. Please help!!!
public class QnA
{
//index of correct answer when calling the getAnswer() method:
public static final int RIGHT_ANSWER = 5;
private Vector question = new Vector ();//contains the questions
private Vector answer1 = new Vector ();//first possible answer
private Vector answer2 = new Vector ();//second possible answer
private Vector answer3 = new Vector ();//third possible answer
private Vector answer4 = new Vector ();//fourth possible answer
private Vector right = new Vector ();//(index)correct answer
public QnA (String UGGR)
{
String s;
/*flag rot determine what is to be read next;
0 - question
1 - first answer
2 - second answer
3 - third answer
4 - fourth answer
5 - correct answer */
int readNow = 0;
try
{
FileReader fsource = new FileReader (UGGR);
BufferedReader bsource = new BufferedReader (fsource);
while((s = bsource.readLine()) != null)
{
s = s.trim(); //remove spaces from both ends of a string
if (s.length() !=0) //ignores empty lines
if (readNow == 0)
{
question.addElement(s);
readNow++;
}
else if (readNow == 1)
{
answer1.addElement(s);
readNow++;
}
else if (readNow == 2)
{
answer2.addElement(s);
readNow++;
}
else if (readNow == 3)
{
answer3.addElement(s);
readNow++;
}
else if (readNow == 4)
{
answer4.addElement(s);
readNow++;
}
else if (readNow == 5)
{
right.addElement(s);
readNow = 0;
}
}
bsource.close();
fsource.close();
if (readNow !=0)
{
System.err.println("File" + "UGGR.txt" + ", last question is incomplete!");
System.exit(1);
}
}
catch (Exception e)
{
System.err.println("Error loading questions: " + e);
System.exit(1);
}
if(getNumberOfQuestions() < 1)
{
System.err.println("No questions loaded!");
System.exit(1);
}
}
public int getNumberOfQuestions()
{
return question.size();
}
public String getQuestion(int index)
{
try
{
return (String) question.get(index);
}
catch (ArrayIndexOutOfBoundsException e)
{
return "NO QUESTION";
}
}
public String getAnswer(int index, int qNumber)
{
try
{
switch(qNumber)
{
case 1:
return (String)answer1.get(index);
case 2:
return (String)answer2.get(index);
case 3:
return (String)answer3.get(index);
case 4:
return (String)answer4.get(index);
case 5:
return (String)right.get(index);
}
}
catch(ArrayIndexOutOfBoundsException e)
{
}
return "NO ANSWER";
}
}