Thursday, April 25, 2013

Quiz program

This is a quiz program. The program allows you to answer up to 10 Java programming basic questions. Then it displays a report that shows all questions, their correct answers, answers selected by the user, and the number of correct answers. The program uses two two-dimensional arrays, one for storing pairs of question and its possible answers, and another one for storing pairs of question and its correct answers. The answer selected by the user of a question is added in the HashMap object for the report.

QuizProgram source code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
class  Quiz extends JFrame implements ActionListener{
            JPanel panel;
            JPanel panelresult;
            JRadioButton choice1;
            JRadioButton choice2;
            JRadioButton choice3;
            JRadioButton choice4;
            ButtonGroup bg;
            JLabel lblmess;
            JButton btnext;
            String[][] qpa;
            String[][] qca;
            int qaid;
            HashMap<Integer, String> map;

1                      initializedata();
2                      setTitle("Quiz Program");
3                      setDefaultCloseOperation(EXIT_ON_CLOSE);
4                      setSize(430,350);
5                      setLocation(300,100);
6                      setResizable(false);
7                      Container cont=getContentPane();
8                      cont.setLayout(null);          
9                      cont.setBackground(Color.GRAY);
10                    bg=new ButtonGroup();     
11                    choice1=new JRadioButton("Choice1",true);
12                    choice2=new JRadioButton("Choice2",false);
13                    choice3=new JRadioButton("Choice3",false);
14                    choice4=new JRadioButton("Choice4",false);
15                    bg.add(choice1);
16                    bg.add(choice2);
17                    bg.add(choice3);
18                    bg.add(choice4);
19                    lblmess=new JLabel("Choose a correct anwswer");
20                    lblmess.setForeground(Color.BLUE);
21                    lblmess.setFont(new Font("Arial", Font.BOLD, 11));
22                    btnext=new JButton("Next");
23                    btnext.setForeground(Color.GREEN);                
24                    btnext.addActionListener(this);
25                    panel=new JPanel();
26                    panel.setBackground(Color.LIGHT_GRAY);
27                    panel.setLocation(10,10);
28                    panel.setSize(400,300);
29                    panel.setLayout(new GridLayout(6,2));
30                    panel.add(lblmess);
31                    panel.add(choice1);
32                    panel.add(choice2);
33                    panel.add(choice3);
34                    panel.add(choice4);
35                    panel.add(btnext);
36                    cont.add(panel);
37                    setVisible(true);
38                    qaid=0;
39                    readqa(qaid);
40        public void actionPerformed(ActionEvent e){
                                    else {
                                                btnext.setText("Show answers");
                        else if(btnext.getText().equals("Show answers"))
                                    new Report();

41        public void initializedata(){
                        //qpa stores pairs of question and its possible answers
                        qpa=new String[10][5];

                        qpa[0][0]="How to run Java program on the command prompt?";
                        qpa[0][1]="javac JavaProgram";
                        qpa[0][2]="java JavaProgram";
                        qpa[0][4]="No one";

                        qpa[1][0]="What is the use of the println method?";
                        qpa[1][1]="It is used to print text on the screen.";
                        qpa[1][2]="It is used to print text on the screen with the line break.";
                        qpa[1][3]="It is used to read text from keyboard.";
                        qpa[1][4]="It is used to read text from a file.";
                        qpa[2][0]="How to read a character from the keyboard?";
                        qpa[2][3]="char c=(char)";
                        qpa[2][4]="char c=(char)";

                        qpa[3][0]="Which one is a single-line comment?";

                        qpa[4][0]="How do you declare an integer variable x?";
                        qpa[4][1]="int x";
                        qpa[4][2]="x as Integer";
                        qpa[4][3]="Int[] x";
                        qpa[4][4]="No one is correct.";

                        qpa[5][0]="How do you convert a string of number to a number?";
                        qpa[5][1]="int num=Integer.parseInt(str_num)";
                        qpa[5][2]="int num=str_num.toInteger()";
                        qpa[5][3]="int num=(int)str_num";
                        qpa[5][4]="int num=(Integer)str_num";

                        qpa[6][0]="What is the value of x? int x=3>>2";

                        qpa[7][0]="How to do exit a loop?";
                        qpa[7][1]="Using exit";
                        qpa[7][2]="Using break";
                        qpa[7][3]="Using continue";
                        qpa[7][4]="Using terminate";

                        qpa[8][0]="What is the correct way to allocate one-dimensional array?";
                        qpa[8][1]="int[size] arr=new int[]";
                        qpa[8][2]="int arr[size]=new int[]";
                        qpa[8][3]="int[size] arr=new int[size]";
                        qpa[8][4]="int[] arr=new int[size]";

                        qpa[9][0]="What is the correct way to allocate two-dimensional array?";
                        qpa[9][1]="int[size][] arr=new int[][]";
                        qpa[9][2]="int arr=new int[rows][cols]";
                        qpa[9][3]="int arr[rows][]=new int[rows][cols]";
                        qpa[9][4]="int[][] arr=new int[rows][cols]";

                        //qca stores pairs of question and its correct answer
                        qca=new String[10][2];
                        qca[0][0]="How to run Java program on the command prompt?";
                        qca[0][1]="java JavaProgram";

                        qca[1][0]="What is the use of the println method?";
                        qca[1][1]="It is used to print text on the screen with the line break.";

                        qca[2][0]="How to read a character from the keyboard?";
                        qca[2][1]="char c=(char)";

                        qca[3][0]="Which one is a single-line comment?";

                        qca[4][0]="How do you declare an integer variable x?";
                        qca[4][1]="int x";

                        qca[5][0]="How do you convert a string of number to a number?";
                        qca[5][1]="int num=Integer.parseInt(str_num)";

                        qca[6][0]="What is the value of x? int x=3>>2";
                        qca[7][0]="How to do exit a loop?";
                        qca[7][1]="Using break";
                        qca[8][0]="What is the correct way to allocate one-dimensional array?";
                        qca[8][1]="int[] arr=new int[size]";

                        qca[9][0]="What is the correct way to allocate two-dimensional array?";
                        qca[9][1]="int[][] arr=new int[rows][cols]";
                        //create a map object to store pairs of question and selected answer
                        map=new HashMap<Integer, String>();
42        public String getSelection(){
                        String selectedChoice=null;
                        Enumeration<AbstractButton> buttons=bg.getElements(); 
                        JRadioButton temp=(JRadioButton)buttons.nextElement(); 

43        public void readqa(int qid){
                        lblmess.setText("  "+qpa[qid][0]);
44        public void reset(){
45        public int calCorrectAnswer(){
                        int qnum=10;
                        int count=0;
                        for(int qid=0;qid<qnum;qid++)
                                    if(qca[qid][1].equals(map.get(qid))) count++;
                        return count;

46        public class Report extends JFrame{
                                    addWindowListener(new WindowAdapter(){
                                                            public void windowClosing(WindowEvent e){
                                    Draw d=new Draw();                                  
47                    class Draw extends Canvas{
                                    public void paint(Graphics g){
                                                int qnum=10;
                                                int x=10;
                                                int y=20;
                                                for(int i=0;i<qnum;i++){
                                                            //print the 1st column
                                                            g.setFont(new Font("Arial",Font.BOLD,12));                                         
                                                            g.drawString(i+1+". "+qca[i][0], x,y);
                                                            g.setFont(new Font("Arial",Font.PLAIN,12));                             
                                                            g.drawString("      Correct answer:"+qca[i][1], x,y);
                                                            g.drawString("      Your answer:"+map.get(i), x,y);
                                                            //print the 2nd column
                                                //Show number of correct answers
                                                int numc=calCorrectAnswer();
                                                g.setFont(new Font("Arial",Font.BOLD,14));
                                                g.drawString("Number of correct answers:"+numc,300,500);



48 public class QuizProgram{
            public static void main(String args[]){
                         new Quiz();


Quiz program in Java

Quiz report

Code Explanation:
1 Initialize questions, possible answers, and correct answers.
2 Set the title of the program window (Quiz Program).
3 Let the program window close when the user clicks the close button.
4 Specify the width and height of the program window when it opens.
5 Specify the location of the program window when it opens.
6 Disable program window resizing.
7 Create a container object to act as the controls placeholder.
8 Set the layout of the container to null so that you can customize the locations of controls to place on it.
9 Set the background color of the container to the gray color.
10 Create the ButtonGroup object to hold the JRadioButton objects.
11-18 Create four JRadioButton objects and add them to the ButtonGroup bg. The radio buttons allows the user to choose the correct answer. The radio buttons are placed in the ButtonGroup to make sure that only one of the four answer choice can be selected.
19 Create a JLabel object lblmess to display the question.
20 Set the text color of the lblmess to the blue color.
21 Set the font name, font style, and font size of the lblshow label.
22 Create the JButton next object to enable next question.
23 Set the text color of the next button tot the green color.
24 Add action event tot button to enable button-click action.
25 Create the JPanel panel object to hold the controls (label, radio buttons, and button).
26 Set the background color of the panel to the light gray color.
27 Specify the location of the panel object.
28 Specify the width and height of panel object.
29 Set the layout of the panel to a grid layout with 6 rows and 2 columns.
30-35 Add all controls to the panel object.
36 Add the panel object to the container.
37 Make sure the program window is visible.
38 Initialize the question id.
39 Display the first question (id=0) and its answers choice to the user.
40 The actionPerformed method of the ActionListener interface is rewritten to handle the button click event.
41 Initialize the qpa and qca arrays. The qpa array  stores pairs of question and its possible answers, and qca array stores pairs of question and its correct answers. The HashMap object also created. It will be uses to store the pairs of question and its selected answer.
42 The getSelection method returns the answer selected by the user from the answer choices list.
43 The readqa method is invoked to set the question to the lblmess, and answer choices text to the four radio buttons. The first radio button is selected by default.
44 The reset method reset the program back to its first load state.
45  The calCorrectAnswer method return the number of answers that are answered correctly.
46  The Report class extends JFrame. The report window is displayed when the user complete all questions and clicks the btnext button (label Show answers).
47 The Draw class extends Canvas. It is an inner class of the Report class. The Draw class is used to display the output to the user.
48 The QuizProgram class the main method to start the Quiz program.


  1. If you want a quiz program that you can add questions easily, visit this page :

  2. do we save this program as or
    I have tried this program but there is an error which says "Class QuizProgram does not have a main method"....need to solve this problem asap

    1. You will save the program as since the QuizProgram class contains the main method..

    2. How do we add gui countdown timer for each question...for example each question should be answered within 1 sec,otherwise it should move to the next one....would appreciate if you could reply asap...thanks in advance

    3. You should create a moveNext method to move to the next question.You will use the Thread.sleep (5000) to delay then call the moveNext method to move to the next question.

  3. Sorry am very new to java...could you please give the code for the timer and where in the program should we insert the code for the gui timer??

  4. You can read the full code from the link below. It delays a question five seconds then automatically move to the next question.

  5. C:\Users\Josh\Documents\ error: class Quiz is public, should be declared in a file named
    public class Quiz extends JFrame implements ActionListener{
    1 error

    Process completed.

    I have one error reply asap plsss!

  6. C:\Users\Josh\Documents\ error: class Quiz is public, should be declared in a file named
    public class Quiz extends JFrame implements ActionListener{
    1 error

    Process completed.

    I have one error reply asap plsss!

  7. --------------------Configuration: --------------------
    Exception in thread "main" java.lang.NullPointerException
    at Quiz.(
    at QuizProgram.main(

    Process completed.

    What does this means?

  8. Hi.. Am new to java. Having a task that timer need to run inside the frame & @ the result Time taken need to be displayed. Can anyone plz help me out ASAP.

  9. nice work these will help me with my school project

  10. Sorry New to JAVA. Is it possible to randomly select questions from a file ?


  11. Hello

    program does not work for me, I think it is connected with this:

    public static void main(String args[]){
    new Quiz();

    Is it possible to access somehow to the full code? Thanks

  12. how does it get the correct answer? i mean if you pick the wrong answer how will the program know it it's right or wrong?

  13. This comment has been removed by the author.

  14. i do agree your blog for quiz programming concepts, which is very helpful to grow up your knowledge. keep sharing more.
    you can get more quiz questions from below link.
    j2ee training in chennai

  15. Great work Sir! But my prof. want the questions to be in jumbled (in different sequence) every time the user restart the quiz program. What part of the program will I edit? What codes will I add? Sir please help.

  16. Nice work bro! Can I ask you for the class diagram of this program? Thanks!

  17. Youth Talent is a social platform for professionals where they can show their talent by managing photo albums, video albums, blog posting and post jobs to seek talent. People can make friends, chat with them and share anything they have in this talent portal to friends or public.socialmedia

  18. Hi All, I would like to have the "Match the following" kind of quiz in swing. Could some one please help on this code

  19. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    Android Training in Chennai
    Ios Training in Chennai

  20. Excellent Post, Interesting Article.Indias Fastest Local Search Engine, you can Search Anything, From anywhere at any time CALL360

  21. how to create a different question if you finished the Quiz?

  22. If your web site is on the discussed server, it'll share server assets along with additional web sites on the same server. This could be the most inexpensive solution, but can result in the worst overall performance if other websites are hogging your sources. These are typically not suggested if you are attempting to run an e-commerce site.I wondered upon your blog and wanted to say that I have really enjoyed reading your blog posts. Any way I’ll be subscribing to your feed and I hope you post again soon.
    Hadoop Training in Chennai
    Big Data Training in Chennai
    Python Training in Chennai
    Python Training Centers in Chennai
    Data Science Training in Chennai
    Data Science Course in Chennai
    Data Analytics Training in Chennai
    Best AngularJS Training in Chennai
    AngularJS Training in Chennai
    QlikView Training in Chennai
    Informatica Training in Chennai

  23. Can u please add bookmark option to this program .... I'm new to java.. I need help...

  24. Quite Interesting. The content is too good and informative. Thanks for sharing.

    Java training in Chennai