Showing posts with label quiz. Show all posts
Showing posts with label quiz. Show all posts

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;

            Quiz(){
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){
           
                        if(btnext.getText().equals("Next")){
                                    if(qaid<9){
                                               
                                                map.put(qaid,getSelection());
                                                qaid++;
                                                readqa(qaid);
                                                }
                                    else {
                                                map.put(qaid,getSelection());
                                                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][3]="javac JavaProgram.java";
                        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][1]="char c=System.read()";
                        qpa[2][2]="char c=System.in.read()";
                        qpa[2][3]="char c=(char)System.read()";
                        qpa[2][4]="char c=(char)System.in.read()";

                        qpa[3][0]="Which one is a single-line comment?";
                        qpa[3][1]="/...";
                        qpa[3][2]="//...";
                        qpa[3][3]="/*...";
                        qpa[3][4]="/*...*/";

                        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[6][1]="1";
                        qpa[6][2]="0";
                        qpa[6][3]="3";
                        qpa[6][4]="-3";

                        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)System.in.read()";

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


                        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[6][1]="0";
                       
                        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(); 
                        while(buttons.hasMoreElements()) 
                        { 
                        JRadioButton temp=(JRadioButton)buttons.nextElement(); 
                        if(temp.isSelected()) 
                                    { 
                                                selectedChoice=temp.getText();
                                    } 
                         }  
                        return(selectedChoice);
            }


43        public void readqa(int qid){
                        lblmess.setText("  "+qpa[qid][0]);
                        choice1.setText(qpa[qid][1]);
                        choice2.setText(qpa[qid][2]);
                        choice3.setText(qpa[qid][3]);
                        choice4.setText(qpa[qid][4]);
                        choice1.setSelected(true);
            }
44        public void reset(){
                        qaid=0;
                        map.clear();
                        readqa(qaid);
                        btnext.setText("Next");
                        }
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{
                        Report(){
                                    setTitle("Answers");
                                    setSize(850,550);
                                    setBackground(Color.WHITE);
                                    addWindowListener(new WindowAdapter(){
                                                            public void windowClosing(WindowEvent e){
                                                                        dispose();
                                                                        reset();
                                                            }
                                                });
                                    Draw d=new Draw();                                  
                                    add(d);
                                    setVisible(true);
                                    }
                       
                       
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);
                                                            y+=30;           
                                                            g.setFont(new Font("Arial",Font.PLAIN,12));                             
                                                            g.drawString("      Correct answer:"+qca[i][1], x,y);
                                                            y+=30;
                                                            g.drawString("      Your answer:"+map.get(i), x,y);
                                                            y+=30;
                                                            //print the 2nd column
                                                            if(y>400)
                                                            {y=20;
                                                              x=450;
                                                            }
                                                           
                                                }
                                                //Show number of correct answers
                                                int numc=calCorrectAnswer();
                                                g.setColor(Color.BLUE);
                                                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.