Hello I need some help completing a quiz program the program simulates a Java quiz I have completed most of the program but there are three issues that i am unable to overcome I tried some of the solutions that i found on daniweb and on google but they didnt work I was hoping someone would be able to help me. This is a quick overview of the program, it has 3 basic parts first it asks the test taker for the personal info once that is provided the quiz starts the quiz ends when the user answers all questions or the time runs out at that point the answers are evaluated.
issue 1- my timer is on a thread (it is required to be on a thread ) how do i call the scoring class once the timer thread is done?
issue 2- when i hit the next button all radio buttons must be unckecked but the previous selected button gets carried over I tied using the clearselected method but the problem is if the user hits the previous button to review a question when he hits next to continue hes answers are cleared forcing the user to have to answer the question again.
issue 3- the user has the option to take the test one more time if he fails the first time so i tried setting a variable to control the number of times he is allowed to take the test incrementing that variable by one everytime the user presses the try again button the problem is once i reload the class that variable gets wiped and returns to the original value.
below is the code if anyone can give me a hand with these issues i will be very grateful.
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Final extends JFrame {
private JLabel title = new JLabel(" Java Quiz");
private JLabel instructionsLN1 = new JLabel("This Quiz will test your knowledge in the different aspects of java."
+ "You will have 10 minutes to answer 20 questions.");
private JLabel instructionsLN3 = new JLabel("Please fill the required information to start.");
private JLabel instructionsLN4 = new JLabel("Good luck. ");
private JLabel nameLabel = new JLabel("Enter you full name: ");
private JLabel idLabel = new JLabel("Enter your student ID: ");
private JTextField nameTF = new JTextField();
private JPasswordField idTF = new JPasswordField(10);
private JButton start = new JButton("Start Test");
private Container c = getContentPane();
private JPanel p = new JPanel();
private Font font = new Font("serif", Font.BOLD, 48);
private String nameString = null;
private String idString = null;
public JLabel clockLB2 = null;
private JPanel titlePN = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JPanel buttonPN = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JPanel instructionsPN = new JPanel();
private JPanel namePN = new JPanel(new GridLayout(2, 2));
private int numberOfTries = 1;
// some quiz components
public String[] questions = new String[700];
public int[][] questionHistory = new int[20][2];
Random randon = new Random();
public int currentQuestion = (int) (randon.nextInt(100));
public int currentHistoryIndex = 0;
public int maxHistoryIndex = 0;
Thread runner = new Thread(new CountDown());
public String[][] studentInfoArray = new String[1][2];
public Final() {
readQuestions();
// instructionsPN.setLayout(new BoxLayout(instructionsPN, BoxLayout.Y_AXIS));
//p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
// Quiz q = new Quiz();
int inte =numberOfTries;
if(inte == 2){
System.out.print("sdfsfsfsf");
}
setBackground(Color.yellow);
setSize(750, 650);
setResizable(false);
setVisible(true);
setLocationRelativeTo(null);
c.setLayout(new BorderLayout());
p.setLayout(new FlowLayout());
title.setFont(font);
title.setForeground(Color.WHITE);
p.setSize(100, 75);
titlePN.setBackground(Color.GRAY);
buttonPN.setBackground(Color.GRAY);
start.setPreferredSize(new Dimension(100, 30));
nameTF.setPreferredSize(new Dimension(110, 30));
idTF.setPreferredSize(new Dimension(110, 30));
p.setLayout(new GridLayout(7, 1));
instructionsPN.add(instructionsLN1);
instructionsPN.add(instructionsLN3);
instructionsPN.add(instructionsLN4);
namePN.add(nameLabel);
namePN.add(nameTF);
namePN.add(idLabel);
namePN.add(idTF);
p.add(instructionsPN);
p.add(namePN);
buttonPN.add(start);
titlePN.add(title);
c.add(titlePN, BorderLayout.NORTH);
c.add(p, BorderLayout.CENTER);
c.add(buttonPN, BorderLayout.SOUTH);
start.addActionListener(new ActionListener() {//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
public void actionPerformed(ActionEvent event) {
nameString = nameTF.getText();
idString = idTF.getText();
if (nameString.equals("") || idString.equals("")) {
JOptionPane.showMessageDialog(Final.this,
"Please fill the required information.", "Missing Information", JOptionPane.ERROR_MESSAGE);
} else {
//readFile(idString);// ------------------------------------->>>>>>>> must reenable
setVisible(false);
Quiz qz = new Quiz();
clockLB2 = qz.getClockLabel();
// runner.start();
}
//<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
}
});
}
public void validateInput() {
if (nameString == null || idString == null) {
JOptionPane.showMessageDialog(Final.this,
"Please provide the required information.", "Error", JOptionPane.ERROR_MESSAGE);
}
}
private void writeToFile(String name, String id, String score, String numberOfTries) {
{
try {
// Create file
BufferedWriter out = new BufferedWriter(new FileWriter("studentInfo.txt", true));
out.write(name);
out.write("\t\t");
out.write(id);
out.write("\t\t");
out.write(score);
out.write("\t\t");
out.write(numberOfTries);
out.newLine();
out.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(Final.this, "Error: " + e.getMessage());
}
}
}
private void readFile(String id) {
try {
BufferedReader read = new BufferedReader(new FileReader("studentInfo.txt"));
String line = null;
try {
while ((line = read.readLine()) != null) {
if (line.contains(id)) {
JOptionPane.showMessageDialog(Final.this,
"Invalid information. Program will now close.", "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
read.close();
} catch (IOException ex) {
}
} catch (FileNotFoundException ex) {
}
}
private void readQuestions() {
try {
BufferedReader read = new BufferedReader(new FileReader("questions.txt"));
String line = null;
int row = 0;
try {
for (int i = 0; i < 700; i++) {
line = read.readLine();
questions[row++] = line;
}
read.close();
} catch (IOException ex) {
}
} catch (FileNotFoundException ex) {
}
}
public class CountDown extends JPanel implements Runnable {
Thread t = new Thread();
public void run() {
int c = 10;
int min = 0;
int sec = 0;
String timem;
String times;
while (c > 0) {
try {
t.sleep(1000);
} catch (InterruptedException e) {
}
c--;
min = c / 60;
sec = c % 60;
if (min < 10) {
timem = "0" + min;
} else {
timem = "" + min;
}
if (sec < 10) {
times = ":0" + sec;
} else {
times = ":" + sec;
}
clockLB2.setText("Time: " + timem + times);
if (sec == 0 && min == 0) {
JOptionPane.showMessageDialog(Final.this,
"You are out of time. IS OVER", "End of Test", JOptionPane.OK_OPTION);
}
}
}
}
// end start <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
//=============================================================================
public static void main(String[] args) {
new Final();
}
public class Quiz extends JFrame {
// private int i = 0, s = 0;
private Container c = getContentPane();
private JButton submitBT = new JButton("Submit");
private JButton nextBT = new JButton("Next");
private JButton previousBT = new JButton("Previous");
// private JButton quitBT = new JButton("Quit");
private JLabel clockLB2 = new JLabel("Time: 10:00");
private JLabel questionCountLB = new JLabel("Question 1 of 20");
private JPanel topPNC = new JPanel(new FlowLayout(FlowLayout.CENTER));
private JPanel bottonPNR = new JPanel(new FlowLayout(FlowLayout.RIGHT));
private Font font = new Font("serif", Font.BOLD, 25);
private JTextField title = new JTextField(" Java Quiz");
// components for question area
private JPanel qa = new JPanel();
private JLabel question = new JLabel("this is where the questions will be");
private String a1 = "choice1";
private String a2 = "choice2";
private String a3 = "choice3";
private String a4 = "choice4";
private String a5 = "choice5";
private JRadioButton rb1 = new JRadioButton(a1, false);
private JRadioButton rb2 = new JRadioButton(a2, false);
private JRadioButton rb3 = new JRadioButton(a3, false);
private JRadioButton rb4 = new JRadioButton(a4, false);
private JRadioButton rb5 = new JRadioButton(a5, false);
private ButtonGroup bg = new ButtonGroup();
Thread runner = new Thread(new CountDown());
public Quiz() {
//System.out.print(runner.getState());
runner.start();
System.out.print(runner.getState());
if(clockLB2.equals("00:00")){
runner.interrupt();
}/*
if(!runner.isInterrupted()){
System.out.print("DEAD");
}else{
System.out.print("ALIVE");
}*/
previousBT.setEnabled(false);
topPNC.setBackground(Color.GRAY);
clockLB2.setForeground(Color.WHITE);
questionCountLB.setForeground(Color.WHITE);
title.setEditable(false);
title.setFont(font);
title.setBackground(Color.red);
title.setForeground(Color.WHITE);
topPNC.add(title);
topPNC.add(questionCountLB);
topPNC.add(clockLB2, FlowLayout.RIGHT);
// implements botton panel
bottonPNR.setBackground(Color.GRAY);
bottonPNR.add(previousBT);
bottonPNR.add(nextBT);
bottonPNR.add(submitBT);
//topPNC.add(quitBT);
// implements question area
//ButtonGroup bg = new ButtonGroup();
qa.setLayout(new GridLayout(6, 1));
bg.add(rb1);
bg.add(rb2);
bg.add(rb3);
bg.add(rb4);
bg.add(rb5);
qa.add(question);
qa.add(rb1);
qa.add(rb2);
qa.add(rb3);
qa.add(rb4);
qa.add(rb5);
question.setText(questions[currentQuestion * 7]);
rb1.setText(questions[(currentQuestion * 7) + 1]);
rb2.setText(questions[(currentQuestion * 7) + 2]);
rb3.setText(questions[(currentQuestion * 7) + 3]);
rb4.setText(questions[(currentQuestion * 7) + 4]);
rb5.setText(questions[(currentQuestion * 7) + 5]);
//Add components to frame
c.setLayout(new BorderLayout());
c.add(topPNC, BorderLayout.NORTH);
c.add(bottonPNR, BorderLayout.SOUTH);
c.add(qa, BorderLayout.CENTER);
setTitle("Final");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
setSize(950, 500);
setResizable(false);
setLocationRelativeTo(null);
// implements submit button
submitBT.setPreferredSize(new Dimension(100, 30));
submitBT.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
runner.stop();// -----> UNSAFE. TRY TO MAKE SAFER STOP
if (JOptionPane.showConfirmDialog(Quiz.this,
"Are you sure you want to submit your answers?", "Submit",
JOptionPane.YES_NO_OPTION) == 0) {
setVisible(false);
new Score();
}
}
});
// implements next button
nextBT.setPreferredSize(new Dimension(70, 30));
nextBT.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
int nextQuestion = -1;
boolean answer = getAnswer(currentQuestion, selectedButton()).equals(getCorrectAnswer(currentQuestion));
questionHistory[currentHistoryIndex][0] = currentQuestion;
questionHistory[currentHistoryIndex][1] = selectedButton();
if (currentHistoryIndex == maxHistoryIndex) {
//generate next question number to use
int currentLevel = currentQuestion / 25;
int nextLevel = currentLevel;
if (answer) {
if (currentLevel < 3) {
nextLevel++;
}
} else {
if (currentLevel > 0) {
nextLevel--;
}
}
while (true) {
int k = 0;
Random randomNum = new Random();
nextQuestion = nextLevel * 25 + (int) (randomNum.nextInt(25));
for (k = 0; k < maxHistoryIndex; k++) {
if (questionHistory[k][0] == nextQuestion) {
break;
}
}
if (k == maxHistoryIndex) {
break;
}
}
currentHistoryIndex++;
maxHistoryIndex++;
if (maxHistoryIndex == 19) {
nextBT.setEnabled(false);
} else {
nextBT.setEnabled(true);
}
} else {
// returning to question already on list
currentHistoryIndex++;
nextQuestion = questionHistory[currentHistoryIndex][0];
int nextAnswer = questionHistory[currentHistoryIndex][1];
setSelectedButton(nextAnswer);
}
if (currentHistoryIndex == 19) {
nextBT.setEnabled(false);
}
currentQuestion = nextQuestion;
questionHistory[currentHistoryIndex][0] = currentQuestion;
questionHistory[currentHistoryIndex][1] = selectedButton();
question.setText(questions[currentQuestion * 7]);
rb1.setText(questions[(currentQuestion * 7) + 1]);
rb2.setText(questions[(currentQuestion * 7) + 2]);
rb3.setText(questions[(currentQuestion * 7) + 3]);
rb4.setText(questions[(currentQuestion * 7) + 4]);
rb5.setText(questions[(currentQuestion * 7) + 5]);
previousBT.setEnabled(true);
//setSelectedButton(questionHistory[currentHistoryIndex][1]);
questionCountLB.setText("Question " + (currentHistoryIndex + 1) + " of 20");
}
});
// implements previous button
previousBT.setPreferredSize(new Dimension(120, 30));
previousBT.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
nextBT.setEnabled(true);
questionHistory[currentHistoryIndex][1] = selectedButton();
currentHistoryIndex--;
if (currentHistoryIndex == 0) {
previousBT.setEnabled(false);
}
if (currentHistoryIndex > 0) {
previousBT.setEnabled(true);
}
int nextQuestion = questionHistory[currentHistoryIndex][0];
currentQuestion = nextQuestion;
question.setText(questions[currentQuestion * 7]);
rb1.setText(questions[(currentQuestion * 7) + 1]);
rb2.setText(questions[(currentQuestion * 7) + 2]);
rb3.setText(questions[(currentQuestion * 7) + 3]);
rb4.setText(questions[(currentQuestion * 7) + 4]);
rb5.setText(questions[(currentQuestion * 7) + 5]);
setSelectedButton(questionHistory[currentHistoryIndex][1]);
questionCountLB.setText("Question " + (currentHistoryIndex + 1) + " of 20");
}
});
/*if(runner.isInterrupted()){
System.out.print("alive");
}else{
System.out.print("dead");
}*/
}
// helper methods
public JLabel getClockLabel() {
return clockLB2;
}
public int selectedButton() {
if (rb1.isSelected()) {
return 0;
}
if (rb2.isSelected()) {
return 1;
}
if (rb3.isSelected()) {
return 2;
}
if (rb4.isSelected()) {
return 3;
}
if (rb5.isSelected()) {
return 4;
}
return -1;
}
public void setSelectedButton(int bNumber) {
if (bNumber == 0) {
rb1.setSelected(true);
}
if (bNumber == 1) {
rb2.setSelected(true);
}
if (bNumber == 2) {
rb3.setSelected(true);
}
if (bNumber == 3) {
rb4.setSelected(true);
}
if (bNumber == 4) {
rb5.setSelected(true);
}
}
public String getAnswer(int qNumber, int bNumber) {
if (bNumber == -1) {
return "";
}
int row = (qNumber * 7) + (bNumber + 1);
return questions[row];
}
public String getCorrectAnswer(int qNumber) {
int row = (qNumber * 7) + (6);
return questions[row];
}
/// end of helper
public class Score extends JFrame {
private int rightCount = 0;
private int wrongCount = 0;
private double score = 0;
private double guessed = 0;
private double guessedPenalty = 0;
private JLabel rightLB;
private JLabel wrongLB;
private JLabel scoreLB;
private JLabel message = new JLabel();
private JLabel scoreTitle = new JLabel("Score");
private JButton finish = new JButton("Exit");
private JButton tryAgain = new JButton("Try Again");
public Score() {
super("SCORE");
setSize(600, 300);
setVisible(true);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Container c = getContentPane();
JPanel displayPN = new JPanel(new GridLayout(4, 1));
JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
JPanel titlePanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
setLayout(new BorderLayout());
setBackground(Color.WHITE);
scoreTitle.setFont(font);
scoreTitle.setForeground(Color.WHITE);
titlePanel.setBackground(Color.GRAY);
buttonPanel.setBackground(Color.GRAY);
for (int i = 0; i <= maxHistoryIndex; i++) {
boolean answer = getAnswer(questionHistory[i][0], questionHistory[i][1]).equals(getCorrectAnswer(questionHistory[i][0]));
if (answer) {
rightCount++;
}
}
if (currentHistoryIndex == 0) {
wrongCount += wrongCount;
rightCount -= rightCount;
}
wrongCount = 20 - rightCount;
//formulas
guessed = (rightCount - wrongCount) / 20;
guessedPenalty = ((1 - guessed) * wrongCount) + wrongCount;
score = (rightCount * 5) - guessedPenalty;
if (score <= 0) {
score = 0;
}
scoreLB = new JLabel("Score: " + score);
rightLB = new JLabel("Correct Answers: " + rightCount);
wrongLB = new JLabel("Wrong Answers: " + wrongCount);
if (score >= 65 && score <= 74.9) {
message.setText("Congratulations. You passed as a Java Certified Programmer. "
+ "Press Exit to save your score.");
displayPN.setBackground(Color.GREEN);
} else if (score > 74.9 && score <= 84.9) {
message.setText("Congratulations. You passed as a Java Certified Developer. "
+ "Press Exit to save your score. ");
displayPN.setBackground(Color.GREEN);
} else if (score > 84.9) {
message.setText("Congratulations. You passed as a Java Certified Architect. "
+ "Press Exit to save your score.");
displayPN.setBackground(Color.GREEN);
} else {
message.setText("Sorry. But you failed the test you may take the test one more time ");
displayPN.setBackground(Color.RED);
}
// Add components to panels then to frame
titlePanel.add(scoreTitle);
displayPN.add(message);
displayPN.add(rightLB);
displayPN.add(wrongLB);
displayPN.add(scoreLB);
buttonPanel.add(finish);
buttonPanel.add(tryAgain);
add(titlePanel, BorderLayout.NORTH);
add(displayPN, BorderLayout.CENTER);
add(buttonPanel, BorderLayout.SOUTH);
finish.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
writeToFile(nameString, idString, String.valueOf(score), String.valueOf(numberOfTries));
System.exit(0);
}
});
tryAgain.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
setVisible(false);
new Final();
numberOfTries++;
}
});
}
}
public class keepTrack{
int KTtries = numberOfTries;
String KTName = nameString;
String KTId = idString;
public int returnTries(){
return KTtries;
}
public String returnName(){
return KTName;
}
public String returnId() {
return KTId;
}
}
}
}