Quiz program


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 8 of 8

Thread: Quiz program

  1. #1
    Join Date
    Nov 2004
    Posts
    8

    Quiz program

    Hi, this is actually a continuation from my previous posted program. Hope u guys out there can help me!
    I'm supposed to come up with a simple quiz program, which consists of the center panel displayin the question (in a pic format), and a textfield to enter the answer at the lower panel. this goes on for a couple of pages and once it is completed, the final page would display the total correct answers out of the number of questions, as well as the score in percentage form.
    The few(or many) problems that i'm facing are :

    1)How do i save the answers that are typed in each textfield? And later on checked for the correct answer based on the array given?

    2)How do i go about doing the final score in percentage form and total of correct answers?

    3)I previously tried out using canvas, but it didnt seem to work. my questions(pictures) that are supposed to displayed in the center(canvas) produce nothing. How do i rectify it?

    i'm really sorry for the mess in the codings, hope this wouldnt be a hassle for any of u out there. Once again thanks in advance!

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    sorry for the mess in the codings
    .. did you forget to post the code ...?
    eschew obfuscation

  3. #3
    Join Date
    Nov 2004
    Posts
    8
    Code:
    import java.applet.Applet;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.image.*;
    import java.io.*;
    import java.net.URL;
    import java.net.*;
    import java.util.Vector;
    import javax.swing.*;
    import java.awt.image.*;
    import java.lang.*;
    import java.awt.Graphics;
    
    public class eg31662 extends Applet implements ActionListener
    {
        Panel panel1, panel2, panel3, panel4, panel5;
        Button login, enter;
        Label inst, top, admin, pass, startLabel;
        TextField adminF, passF, field;
        String Admin, Password;
        Vector admins, passwords;
    
    	//Quiz declarations
    
    	TextField ansF1,ansF2,ansF3;
    	Button startBut, next0, next1, finishB, previous1;
    	Image q1, q2, q3;
    	Image ques[] = new Image[2];
    	boolean text = false;
    	boolean checked = false;
    	int correct = 0;
    	String [] answer = new String [2];
    	String [] solution = {"11", "22", "33"};
    
    	/*
    	boolean text = false;
    	boolean sound = true;
    	int red,green,blue;
    	int question =0;
    	int good = 0;
    	boolean pause= false;
    	boolean start = true;*/
    
        Thread thread = null;
        boolean status = false;
    
        public void init()
        {
            validateUser();
            setLayout (new BorderLayout());
    
            panel1 = new Panel(new FlowLayout());
            panel2 = new Panel(new FlowLayout());
            panel3 = new Panel(new FlowLayout());
    
            //login button
            login = new Button("Login");
    
            //instruction
            inst = new Label("Please type in your UserName and the given " +
                             "password in order to proceed");
    
            //label
            top = new Label("Top Label");
            admin = new Label("User Name :");
            pass = new Label("Password :");
    
            //input textfields
            adminF = new TextField(8);
            passF = new TextField(10);
            passF.setEchoChar('*');
    
            panel1.setBackground(Color.gray);
            panel2.setBackground(Color.orange);
    		panel3.setBackground(Color.gray);
    
            panel2.add(admin);
            panel2.add(adminF);
            panel2.add(pass);
            panel2.add(passF);
            panel2.add(login);
            panel3.add(inst);
    
            panel1.add(top);
    
            add(panel1, BorderLayout.NORTH);
            add(panel2, BorderLayout.CENTER);
            add(panel3, BorderLayout.SOUTH);
    
            login.addActionListener(this);
    
            setSize(500,400);
        }
    
        private void validateUser()
        {
            String[] adminData    = {"t", "User1", "User2", "User3"};
            String[] passwordData = {"t", "P1", "P2", "P3"};
            admins = new Vector();
            passwords = new Vector();
            for(int j = 0; j < adminData.length; j++)
            {
                admins.add(adminData[j]);
                passwords.add(passwordData[j]);
            }
        }
    
        private void Mainpage()
        {
            boolean flag = true;
            removeAll();  // remove all components from container
            panel1 = new Panel(new FlowLayout());
            panel2 = new Panel(new FlowLayout());
    		panel3 = new Panel(new FlowLayout());
    
            top = new Label("Welcome");
            enter = new Button("Enter");
    
            panel2.setBackground(Color.orange);
            panel1.setBackground(Color.gray);
            panel3.setBackground(Color.gray);
    
            startLabel = new Label("Welcome! " +
            						"Please click on the 'Start' button to begin the quiz ");
    		startBut = new Button("Start");
    		startBut.requestFocus();
    		Dimension dim = getSize();
    		startBut.setSize(50,20);
    
            add(panel1, BorderLayout.NORTH);
            add(panel2, BorderLayout.CENTER);
            add(panel3, BorderLayout.SOUTH);
    
            panel2.add(startLabel);
            panel2.add(startBut);
    
            startBut.addActionListener(this);
            validate();
            repaint();
        }
    
        private void Quiz1()
        {
    		//quizCanvas = new Canvas();
            boolean flag = true;
            removeAll();  // remove all components from container
            panel1 = new Panel(new FlowLayout());
            panel2 = new Panel(new FlowLayout());
            panel3 = new Panel(new FlowLayout());
    
            panel1.setBackground(Color.gray);
            panel2.setBackground(Color.orange);
            panel3.setBackground(Color.gray);
    
            add(panel1, BorderLayout.NORTH);
            add(panel2, BorderLayout.CENTER);
            add(panel3, BorderLayout.SOUTH);
    
    		q1 = getImage(getDocumentBase(), "1.gif");
    
    		ques[0] = q1;
    		//ques[1] = q2;
    
    		//previous = new Button("<");
    		next0 = new Button("Done");
            ansF1 = new TextField(25);
    		next0.addActionListener(this);
    
    		//quizCanvas.insert(ques1);
    
            //panel3.add(previous);
            panel3.add(next0);
            panel3.add(ansF1);
            //panel2.add("1.gif");
    
    		ansF1.requestFocus();
    		ansF1.setText("focussing");
    
    
            validate();
            repaint();
    
    	}
    
    	public void Quiz2(){
    
            boolean flag = true;
            removeAll();  // remove all components from container
            panel1 = new Panel(new FlowLayout());
            panel2 = new Panel(new FlowLayout());
            panel3 = new Panel(new FlowLayout());
    
            panel1.setBackground(Color.gray);
            panel2.setBackground(Color.orange);
            panel3.setBackground(Color.gray);
    
            add(panel1, BorderLayout.NORTH);
            add(panel2, BorderLayout.CENTER);
            add(panel3, BorderLayout.SOUTH);
    
    		q2 = getImage(getDocumentBase(), "2.gif");
    
    		ques[1] = q2;
    
    		next1 = new Button("Done");
            ansF2 = new TextField(25);
    		next1.addActionListener(this);
    
            panel3.add(next1);
            panel3.add(ansF2);
    
    		ansF2.requestFocus();
    		ansF2.setText("focussing");
    
    
            validate();
            repaint();
    
    	}
    
    	public void Quiz3(){
    
            boolean flag = true;
            removeAll();  // remove all components from container
            panel1 = new Panel(new FlowLayout());
            panel2 = new Panel(new FlowLayout());
            panel3 = new Panel(new FlowLayout());
    
            panel1.setBackground(Color.gray);
            panel2.setBackground(Color.orange);
            panel3.setBackground(Color.gray);
    
            add(panel1, BorderLayout.NORTH);
            add(panel2, BorderLayout.CENTER);
            add(panel3, BorderLayout.SOUTH);
    
    		q3 = getImage(getDocumentBase(), "3.gif");
    
    		ques[2] = q3;
    
    		finishB = new Button("Finish");
            ansF3 = new TextField(25);
    		finishB.addActionListener(this);
    
            panel3.add(finishB);
            panel3.add(ansF3);
    
    		ansF3.requestFocus();
    		ansF3.setText("focussing");
    
    
            validate();
            repaint();
    
    
    	}
    
    
        public void start() {
            if(thread == null) {
                status = true;
            }
        }
    
        public void stop() {
            status = false;
        }
    
    
        public void actionPerformed(ActionEvent ev)
        {
            boolean ok = true;
            if(ev.getSource() == login)
            {
                Admin = adminF.getText();
                Password = passF.getText();
    
                for (int i = 0; i < admins.size(); i++) {
    
                    if (Admin.equals(admins.get(i).toString())) {
                        if (Password.equals(passwords.get(i).toString())) {
                            ok = true;
    
                            JOptionPane.showMessageDialog(null,
                                        "Welcome, u have successfully logged in");
                            Mainpage();
                            break;
                        }
                        else {
                            ok = false;
                        }
                    }
                    else {
                        ok = false;
                    }
                }
    
                if (!ok) {
                    JOptionPane.showMessageDialog(null,
                                  "Incorrect Password or Admin No, Please Try Again",
                                  "Access Denied",
                                   JOptionPane.ERROR_MESSAGE);
                }
            }
    
            if(ev.getSource() == startBut)
            {
    			Quiz1();
    		}
    
    		if (ev.getSource () == next0) {
    
    
    			saveanswer();
    			Quiz2();
    		}
    
    		if (ev.getSource () == next1) {
    
    			//saveanswer();
    			Quiz3();
    
    		}
    
    		if (ev.getSource () == finishB) {
    
    			//saveanswer();
    			//checkanswer();
    		}
    
        }
    
    	/*class quizCanvas extends Canvas {
    
    		private Image quest;
    
    		public quizCanvas() {
    			this.quest = null;
     		}
    
    		public quizCanvas(Image quest) {
    			this.quest = quest;
    		}
    
    		public void insert(Image quest) {
    			this.quest=quest;
    			repaint();
    		}
    
    		public void paint(Graphics g) {
    
    
    		}
    	}*/
    
    
    	public void checkanswer() {
    		if (!checked) {
    		/*question = 0;
    			for (int a=1;a<16;a++) {
    				question++;*/
    				if (ansF1) {
    					if (answer[1].toUpperCase().equals(solution[1])) {
    						correct++;
    					}
    				}
    
    				if (ansF2) {
    					if (answer[2].toUpperCase().equals(solution[2])) {
    						correct++;
    					}
    				}
    
    				if (ansF3) {
    					if (answer[3].toUpperCase().equals(solution[3])) {
    						correct++;
    				}
    
    		checked = true;	}
    		}
    	}
    
    	public void saveanswer() {
    
    		if (text) {
    			if (!ansF1.getText().equals("")) {
    				answer [Quiz1] = ansF1.getText();
    			//answer2[question] = tf2.getText();
    			}
    
    			if (!ansF2.getText().equals("")) {
    				answer [] = ansF2.getText();
    			}
    
    			if (!ansF3.getText().equals("")) {
    				answer [] = ansF3.getText();
    			}
    		}
    	}
    
    }

  4. #4
    Join Date
    Nov 2004
    Posts
    8
    LOL, sorry, was figuring out how to put code tags again...

  5. #5
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    I just hacked up this (in the spirit of Object Oriented
    design )
    The QQA object Ive coded here
    also include a text answer, but it is not used.

    If it bugs out pls let me know.



    Code:
    import javax.swing.*;
    import java.io.*;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    /**
      * A quizgame
      */
    public class QuizGame extends JFrame implements ActionListener  {
      // **************************** static part
      // make a static array of three QQA objects
      static QQA qqa [] = {
        new QQA(1, "Is this an elephant ?","no","monkey.gif"),
        new QQA(2, "What does this guy leave in the woods ?","****","bear.gif"),
        new QQA(3, "Is this guy cool ?","no","saddam.gif")
      };
      // ****************** end of static part
      int qNo=0;
      FileImage getter=new FileImage ();
    
      BorderLayout borderLayout1 = new BorderLayout();
      ImageDisplayPan imgPan = new ImageDisplayPan();
      JPanel jPanel2 = new JPanel();
      JTextField answerTF = new JTextField();
      JButton replyBtn = new JButton();
      JButton closeBtn = new JButton();
    
      Image finitoImage=null;
    
      public QuizGame() {
        try {
          jbInit();
          replyBtn.addActionListener(this);
          closeBtn.addActionListener(this);
          for (int i=0;i<qqa.length;i++) {
            qqa[i].loadImage(getter, this);
          }
          finitoImage=getter.readImageData("finito.gif",this);
          this.imgPan.setImage(qqa[0].getImage());
          showNextQuestion ();
        }
        catch(Exception e) {
          e.printStackTrace();
        }
      }
      public void showNextQuestion () {
        try {
          if (qNo == qqa.length) { // finished, sum it up
    
            int accum=0;
            for (int i=0;i<qqa.length;i++) {
              accum+= (qqa[i].isCorrect()) ? 1: 0;
            }
            double correctness=100.0d*(double)accum/(double)qqa.length;
            // This could be a classic idiot/einstein....
            // depending on the correctness, just a suggestion...
            this.imgPan.setImage(finitoImage);
    
            JOptionPane.showMessageDialog(this,
                                          "You scored: "+correctness+"% on the test",
                                          "Quiz Completed",
                                          JOptionPane.INFORMATION_MESSAGE);
            qNo = 0;
          }
          qqa[qNo].setAnswer(this.answerTF.getText().trim());
          qNo++;
          this.imgPan.setImage(qqa[qNo].getImage());
          this.answerTF.setText("");
        }
        catch (Exception ex) {
          JOptionPane.showMessageDialog(this,
                                      ex.getMessage(),
                                      "DAMM!!",
                                      JOptionPane.ERROR_MESSAGE);
        }
      }
    
      private void jbInit() throws Exception {
        this.getContentPane().setLayout(borderLayout1);
        answerTF.setToolTipText("");
        answerTF.setText("");
        answerTF.setColumns(22);
        replyBtn.setText("Reply");
        closeBtn.setText("Close");
        imgPan.setBorder(BorderFactory.createEtchedBorder());
        this.getContentPane().add(imgPan, BorderLayout.CENTER);
        this.getContentPane().add(jPanel2,  BorderLayout.SOUTH);
        jPanel2.add(closeBtn, null);
        jPanel2.add(answerTF, null);
        jPanel2.add(replyBtn, null);
      }
      public void actionPerformed(ActionEvent e) {
        if (e.getSource()==closeBtn) System.exit(0);
        showNextQuestion ();
      }
      public static void main(String[] args) {
        QuizGame quizGame = new QuizGame();
        quizGame.setBounds(10,10,400,400);
        quizGame.setVisible(true);
      }
    
    }
    
    
    /**
     * Reads image bytes from a file and creates an Image object.
     */
    class FileImage {
    
      private int nBytes=-1;
      private Image img=null;
    
      public Image readImageData (String filePath, JFrame frame) {
        try {
          FileInputStream fi=new FileInputStream(filePath);
          nBytes=fi.available();
          byte [] imageBytes=new byte[nBytes];
          fi.read(imageBytes);
          fi.close();
          img=Toolkit.getDefaultToolkit().createImage(imageBytes);
          MediaTracker mt=new MediaTracker(frame);
          mt.addImage(img,0);
          try {
              mt.waitForID(0); // cant use it until it's ready....
          } catch (InterruptedException ex) {
            ex.printStackTrace();
            tellError(ex, frame);
            return null;
          }
          return img;
        } catch (Exception ex) { // probably IOException
          ex.printStackTrace();
          tellError(ex, frame);
          return null;
        }
      }
      private void tellError (Exception ex, JFrame frame) {
        JOptionPane.showMessageDialog(frame,
                                      "Image load failed:\n"+ex.getMessage(),
                                      "Error",
                                      JOptionPane.ERROR_MESSAGE);
      }
    }
    /**
     *  Quiz question and answer
     */
    class QQA  {
      public int questionNo=-1;
      private String question=null;
      private String correctAnswer=null;
      private String imagePath=null;
      private Image qImage=null;
      private String answer=null;
    
    
      public QQA() {}
      public QQA (int questionNo, String question,
                  String correctAnswer, String imagePath) {
        this.questionNo=questionNo;
        this.question=question;
        this.correctAnswer=correctAnswer;
        this.imagePath=imagePath;
      }
      public void clear() {
        this.answer=null;
      }
      public boolean isCorrect () throws Exception {
        if (this.answer==null) {
          throw new Exception("Question: " + this.toString() + " is not answered");
        }
        return this.answer.toLowerCase().equals(this.correctAnswer.toLowerCase());
      }
      public void setAnswer(String answer) throws Exception {
        this.answer=answer;
      }
      public void loadImage (FileImage getter, JFrame frame) throws Exception {
        this.qImage=getter.readImageData(this.imagePath, frame);
        if (this.qImage==null) throw new Exception ("Failed to load:"+this.imagePath);
      }
      public Image getImage() {
        return this.qImage;
      }
    }
    /**
     * A JPanel extension for displaying images
     */
    
    class ImageDisplayPan extends JPanel {
      protected Image img=null;
      protected JFrame pFrame=null;
      public ImageDisplayPan() {}
      public void setImage(Image img) {
        this.img=img;
        this.setPreferredSize(new Dimension(img.getWidth(this),
                                            img.getHeight(this)));
        repaint();
      }
      public Image getDisplayedImage() {
        return this.img;
      }
      public void update(Graphics g) {
        Color c=g.getColor();
        g.setColor(Color.white);
        g.fillRect(0,0,this.getSize().width,this.getSize().height);
        g.setColor(c);
        if (img!=null) {
          g.drawImage(this.img,0,0,this);
        }
      }
      public void paint(Graphics g) {
        update (g);
      }
    }
    eschew obfuscation

  6. #6
    Join Date
    Nov 2004
    Posts
    8
    Hey there sjalle, thx for the help that's a lot of work you've done there.Much appreciated! have yet to try it out though, but one thing is....i need it in an applet form....and without any JFrames or JPanels.....its juz part of the requirements of my project....

  7. #7
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Not much, I had alle the classes from before, except for
    QQA.

    An applet w. no panels ? Is the requirement that youš
    shall draw images in the same panel (applet) that
    contains the answer textfielld ? That sounds somewhat
    unreasonable to me (like taking a drivers test
    facing backwards...) and in that case I'm out.

    If not, then all you have to do is change the JFrame to
    an Applet, add the init, start/stop methods, skip the
    FileLoader and get the images via the applets getImage
    method.

    For safety you can also swap the J... classes to the old
    awt set (TextField, Button, Panel, Applet..) and leave out
    the swing include directive from the header.
    eschew obfuscation

  8. #8
    Join Date
    Nov 2004
    Posts
    8
    LOL sorry for the confusion caused, i am required to use Panel,Button etc without J's, and like wat u have said earlier, not including the swing directive.
    Nonetheless, thanks for the help! gotta try running it as an applet 1st, i'll get back to u when i've hit a dead end

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center