Computer Science Canada

Making a quiz

Author:  Qamar [ Tue Mar 25, 2008 8:32 am ]
Post subject:  Making a quiz

Hi, i'm taking a gr. 11 computer information science course and i need help plz. =)

Our teacher has told us to make a multiple choice quiz that has 30 questions and it randomly selects 25 of those questions then tells us what % of a mark we got... and he's barely taught us anything.. can anyone help me here .. or where to even start ?

thanks

Author:  Tony [ Tue Mar 25, 2008 9:45 am ]
Post subject:  RE:Making a quiz

you start with making a "quiz" made up of one question, then place that into a 25 step loop. If you do it right, there is _very little_ code that you need to write.

Author:  Qamar [ Mon Mar 31, 2008 7:30 pm ]
Post subject:  Re: Making a quiz

okay... i see how you saying to do this... but i don't have a clue on how to.. haha. like i said. our teacher hasn't taught us much and is expecting us to know stuff

this is my code so far... he said its okay to have them in the terminal window. but he'd give us more marks if we could get them in a dialog box or make an applet with radio buttons

import java.io.*;

public class Quiz {
public static void main(String[] args) throws IOException {
//Create instances of the InputStream and BufferedReader
InputStreamReader reader = new InputStreamReader(System.in);
//Buffer the inputstream
BufferedReader buffer = new BufferedReader(reader);

float mark = 0;
float percent = 0;
String seeker;

System.out.println("Welcome to Qamar and Matt's Java Quiz...");
//Reference the buffer.readLine() command to seeker to grab the input
//Must use the equals method to compare strings == is invalid
//seeker.equalsIgnoreCase(String) takes input regardless of lowercase and uppercase so m is equal to M

System.out.println(" ");
System.out.println("Question 1");
System.out.println("What does OOP stand for ??");
System.out.println("A. Object Oriented Programming");
System.out.println("B. Official Organized Police");
System.out.println("C. Origins of Packets");
System.out.println("D. It doesn't stand for anything");
seeker = buffer.readLine();

if(seeker.equalsIgnoreCase("a"))
{
mark = mark+ 1;
}

System.out.println(" ");
System.out.println(" ");
System.out.println("Question 2");
System.out.println("Which line of code prints out words");
System.out.println("A. Print.String.");
System.out.println("B. System.out.println");
System.out.println("C. system.out.println");
System.out.println("D. That's RIDICULUS");
seeker = buffer.readLine();

if(seeker.equalsIgnoreCase("b"))
{
mark = mark + 1;
}
percent = mark / 2 ;
percent = percent * 100;
System.out.println("your score is: " + mark + " out of 2 which is " + percent + "%");

}
}



Quote:

Author:  CooKieLord [ Fri Apr 04, 2008 8:24 pm ]
Post subject:  Re: Making a quiz

1. It would be awesome if you posted your code in [code] [/code] tags.
2. I would super-impose two arrays. One would be your bank of questions, and the other would be your answer key.

Author:  Euphoracle [ Sat Apr 05, 2008 8:26 am ]
Post subject:  RE:Making a quiz

Doing it the way you are doing it will leave you with 1000+ lines that someone else (this is was Tony was getting at) can do in about ~30 give or take line breaks. If your teacher thinks this is the best way of doing it, then you're going to have a serious problem next year. If you haven't consulted your teacher, do so. Don't be afraid to show your teacher your abilities and ask them for suggestions on how to improve. If you teacher has any capabilities in this subject, he/she should be able to help you change your code from what it is now (repetitive and unnecessary) to efficient and dare I say it, short.

Author:  Barbarrosa [ Sat Apr 05, 2008 4:32 pm ]
Post subject:  Re: Making a quiz

Here are some recommendations, if you have to do this the hard way (you'll end up with < 300 lines, < 100 if you're fairly good, < 50 if you do the easy way well)

Assumptions to fill (for the hard way):

1. Is a specific number of possible answers given to all questions?
2. Terminal or GUI App?
3. Quiz loaded from file or embedded in program?
A. If from file, how to expect input? Make a file organized as such.
B. If embedded, how to create it
C. If embedded, whether you need to make a serious quiz, one with varying questions, or just show that you can use java
to make one.
4. Is the user always assumed to give valid input? (protecting from bad input could save you a lot of trouble)
5. If GUI, is there a next button, or is it automatically changed when an option is selected?
6. How should the final output be organized (GUI or terminal)?
A. Grade: 100%, 98.6%, 14.54% ?
B. List Answers to Questions?
C. Other Information?

Recommended classes to use:

Reading in from file: BufferedReader/InputStreamReader
Reading from terminal input: Scanner
Formatting Numbers: java.text.NumberFormat
GUI: Anything in java.awt.* or javax.swing.* (latter contains lightweight components)

Author:  Qamar [ Tue Apr 08, 2008 8:10 am ]
Post subject:  Re: Making a quiz

hey... so i won't lie.. i don't know what half of those mean... all i know is that i'm going to do it in a terminal window, teacher said he'd give us more marks to get it done in a dialog box but this project is already like 2 weeks past due. could someone help me here ? how do i create a random generator that would make numbers between 0 - 30 and only pick 25 ?


code:
import java.io.*;
import java.util.Random;
public class MCE {
   
  public static void main(String[] args) throws IOException {
      InputStreamReader reader = new InputStreamReader(System.in);
       BufferedReader buffer = new BufferedReader(reader);
     
     String[] Qs = {"An object...","Objects preform actions by executing...", "An Object..."};
     String[] As = {"A) Represents useful data.","A) Methods.", "A) Represents useful data" };
     String[] Bs = {"B) Preforms actions.","B) Actions", "B) Perfroms Actions"};
     String[] Cs = {"C) Both A and B.","C) Procedures", "C) Both A and B"};
     String[] Ds = {"D) None of the above.","D) Events", "D) None of the above"};
     
      String seeker;
      int cntr = 0;
      float mark = 0;
      int Qcount = 0;
      float percent = 0;
 
         
      while (cntr < 3){

     System.out.println (Qs[r]); // r is the variable that will produce a random number thingy.?
     System.out.println (As[r]);
     System.out.println (Bs[r]);
     System.out.println (Cs[r]);
     System.out.println (Ds[r]);

     seeker = buffer.readLine();
     Qcount = Qcount + 1;
     cntr = cntr+1;
     
     /*if(seeker.equalsIgnoreCase("c"))
          {
              mark = mark + 1;
            }
       */
    percent = mark / Qcount;
    percent = percent * 100;
    percent = Math.round (percent);
    System.out.println("Your score is: " + mark + " out of " + Qcount + " which is " + percent + "%");

       }
      }
    }

Author:  Barbarrosa [ Wed Apr 09, 2008 3:04 am ]
Post subject:  Re: Making a quiz

code:

import java.util.Random;
...

Random rand = new Random();
int[] randInts = new int[25];
for(int i = 0; i < 25; i++)
       randInts[i] = rand.nextInt(30) + 1;

Author:  Nick [ Wed Apr 09, 2008 3:23 am ]
Post subject:  RE:Making a quiz

Barbosa, two errors.

1: 30 + 1 = 31 > max questions

2: say it picks 3 twice, that's not very professional

Author:  Barbarrosa [ Wed Apr 09, 2008 3:38 am ]
Post subject:  Re: Making a quiz

Sorry, woops. Wrong assumptions. This will give you 25 numbers, each between 1 and 30, none equivalent to the next, in an int array.
code:

import java.util.Random;
...
//begin method
Random rand = new Random();
int[] randInts = new int[25];
int recI = 0;
for(int i = 0; i < 25; i++){
       recI = rand.nextInt(30) + 1;  //You'll probably want it to remove the +1 if you're using an array to store questions, because an array starts at zero
       if (arrayContains(randInts, recI)){
              i--;
              continue;
       }
       randInts[i] = recI;

}
return randInts;
//end method

private boolean arrayContains(int[] a, int i){
       for(int o = 0; o < a.length; o++)
              if(i == a[o])
                     return true;
       return false;
}


Quote:

Barbosa, two errors.

1: 30 + 1 = 31 > max questions

2: say it picks 3 twice, that's not very professional


1. Random's nextInt(int) method returns an integer between 0 & int-1

2. Fixed here. I wish the arrays in java had a contains(int) method.

Author:  Qamar [ Wed Apr 09, 2008 8:37 am ]
Post subject:  Re: Making a quiz

okay that is sick... but could you tell me how to implement that into my code ?. haha i've spent my whole comp. sci class (75mins) trying to get it to work... but with no success

Author:  Barbarrosa [ Thu Apr 10, 2008 4:07 pm ]
Post subject:  Re: Making a quiz

1. Give more significant names to your variables, even if they are longer
These don't make much sense:

    String seeker;
    int cntr = 0;
    int Qcount = 0;

What's seeker doing in a quiz program? What's cntr? Why is Qcount capitalized, and why isn't numQuestions or questionCount used?

2. Use for statements like:
code:

for(T i:T[]){} // T represents the type - int, float, String, etc. Replace T[] with an array of that type.
for(int i = 0; i < array.length;i++){}


3.Use methods to divide up complex tasks:
code:

private boolean intArrayContains(int[] a, int i){
       for(int o = 0; o < a.length; o++)
              if(i == a[o])
                     return true;
       return false;
}


4. Explore the javadocs online - java has classes and interfaces for lots of things.

    java.util.Scanner
    java.text.NumberFormat

Author:  Qamar [ Tue Apr 15, 2008 8:59 pm ]
Post subject:  Re: Making a quiz

okay cool... so i've explored some different stuff and i decided to put everything into an array... my only problem is i don't know how to set parametors on the random integer and also so that it won't repeat the same quesitons... my code so far is

code:

/**
 * A quiz that asks you  25 questions randomly out of 30
 * By: Qamar, Matt and Steven
 */
import javax.swing.*;// imports the superclass that allows for use of GUI
import java.util.Random;
//import java.io.*;

public class Quizrr { //
public static void main(String[] args) {//
     
     String[] Qs = {"An object...","Objects preform actions by executing...", "Which line of code is correct?","What does OPP stand for ?"};
     String[] As = {"1) Represents useful data.","1) Methods.", "1)System.out.PRINT ","1) Official Programming Protocol" };
     String[] Bs = {"2) Preforms actions.","2) Actions", "2) SYSTEM.out.Print","2) Object Oriented Programming"};
     String[] Cs = {"3) Both A and B.","3) Procedures", "3) system.Out.Print","3) Ontario Programming Police"};
     String[] Ds = {"4) None of the above.","4) Events", "4) System.out.print","4) Objective Protocol Packets"};
       int [] answer = {3,2,4,2};
   
    int count = 0;
    String ans;
    float mark = 0;
    float percent = 0;
    int ans2 ;
   
        while (count < 4) {


            Random r = new Random();
            int randint = r.nextInt(4); // this will pick 1 less than what is in the brackets (n - 1)
           

        ans = JOptionPane.showInputDialog("" + Qs[randint] + "\n"
            +"" + As[randint] + "\n"
            +"" + Bs[randint] + "\n" 
            +"" + Cs[randint] + "\n" 
            +"" + Ds[randint] + "\n" );
            ans2 = Integer.parseInt(ans);

               
    if (ans2 == answer[randint])
                   
        {
            mark = mark+ 1;
        }


        count = count + 1;
    } // end loop
   
   
percent = mark / count;
percent = percent * 100;
percent = Math.round (percent);
JOptionPane.showMessageDialog(null,"Your score is: " + mark + " out of " + count + " which is " + percent + "%");// diplays a pop-up that has the final information
   
           } // end method
        } // end class


and yeah. everything is okay except for the random integer selection... i saw the code from before... but i don't understand the rest of it

Author:  wtd [ Wed Apr 16, 2008 12:44 am ]
Post subject:  RE:Making a quiz

Try to use an array of objects rather than parallel arrays.

Author:  Qamar [ Wed Apr 16, 2008 3:59 pm ]
Post subject:  Re: Making a quiz

okay. never mind. my teacher said that it would be a better idea if i could just shuffle the arrays at the beginning of the program so that they don't go in order each time... how would i do that ? and keep the Questions and answers and possible answers the same ?

Author:  Barbarrosa [ Thu Apr 17, 2008 12:39 am ]
Post subject:  Re: Making a quiz

What wtd is probably talking about is making a class for each question, with the corresponding answers given you would create a class, each with the required number of answers, a correct answer (maybe a String or char), and constructor(String ques, String a, String b...), toString() & returnCorrect(String) methods. Then create a method that chooses random questions, much like the one I put together above.This is probably an answer to your problem of randomly ordering them.

After you have put together a question class, store the questions in it by instantiating all of them at the beginning of the main method (or in another method that is called at the beginning of the main method) and then randomizing them.

Btw, if you're making a gui, you may want to simplify by separating the gui components from the non-gui components. To preserve a more true object-orientation, you could create a constructor for the quiz class and give the frame a pre-made gui with Quiz(frame). Additionally, you will probably need to give your gui a specific layout, add ActionListeners to the choices (& next button, if you have one), and various other things that just come with it. Show me your code after you've worked on it some more.

Author:  Qamar [ Tue Apr 29, 2008 8:15 am ]
Post subject:  Re: Making a quiz

okay so i finished my assignment. and this is how it went...




code:
/**
 * Created By: Qamar
 * This program creates a quiz out of 30 questions and
 * randomly selects 25 questions and then tells you your answer.
 * Created: April 17 2008
 */

import javax.swing.*;// imports the superclass that allows for use of GUI
import java.util.Random; // imports the random class

public class Java_Quiz { //
public static void main(String[] args) {//
 
     String[] Qs = {"What does OOP stand for?", "Which line of code prints out words?", "How do you comment a line in Java?", "Which line converts the string input into a float?", "How do you make an integer?", "What does ??args?? stand for?", "What kind of programming language does Java use?", "How would you print ??Hello?? on the screen?", "How does Bluej accept the value ??x1?? as an integer?", "What does FLOAT do (when insterted into the program properly)?", "What does % do?", "How would you square root x1?", "How do you print on a line?", "How do you make the program accept the name?", "What do you put at the end of a piece of code?", "What can a string do?", "What is missing with this line of code?: ??num = 5(4);??", "What do you start a string or class with?", "What does commenting do?", "What is the proper term to randomize?", "How does ?while? work, when inserted into the code correctly?", "What should go at the top of your program?", "How do you import all of the Java classes?", "Java programming language can run on any platform because...", "What is the purpose of the main method?", "What does ?System.out.print? do?", "When trying to add marks in a multiple choice quiz, what statement would work?", "A class cannot be declared...", "Following code will result in: class A { int b = 1; public static void main(String [] args) { System.out.println(?b is ? + b); }}", "Following code will result in: int a1 = 5; double a2 = (float)a1; ..."};
     String[] As = {"1) Official Or Protocol", "1) Print.String.", "1) //", "1) num = Float.parse (reader.readLine())", "1) int num1;", "1) an onomatopoeia", "1) Object-Orientated", "1) put ??Hello??", "1) get x1;", "1) it makes it possible to have a decimal value with a whole number", "1) divides a number", "1) SquareRoot(x1):", "1) System.out.print(line)", "1) name = (reader.readLine());", "1) /", "1) can hold numbers (it?s numerical value) and words", "1) +", "1) {", "1) changes an integer into a double", "1) randomize", "1) while works like an ??if?? and a loop", "1) your name", "1) import java.io.*;", "1) Java is written in C++", "1) To build a user interface", "1) lets you write something while the program is running", "1) while", "1) Static", "1) Complication error", "1) Compilation error"};
     String[] Bs = {"2) Object Oriented Programming", "2) System.out.println", "2) %", "2) num = float.parse (reader.readLine())", "2) make an int num1;", "2) an argument", "2) Array", "2) put (??Hello??)", "2) accept x1;", "2) it makes the program lighter", "2) multiplies a number", "2) Math.sqrt(x1);", "2) System.out.println", "2) name = (reader.readline());", "2) :", "2) can only hold numbers", "2) /", "2) (", "2) allows others to rate your coding skills", "2) randint", "2) while works like a loop", "2) the date", "2) JavaImportAll;", "2) The Java Virtual Machine1(JVM) interprets the program for the native operating system", "2) To create buttons and scrollbars", "2) lets you write something before you run the program", "2) if", "2) Private", "2) Runtime exception", "2) Runtime error"};
     String[] Cs = {"3) Ontario Organized Police", "3) system.out.println", "3) \\", "3) num = Float.parseFloat(reader.readLine())", "3) integer num1;", "3) it stands for nothing", "3) Logic", "3) System.out.print(??Hello??);", "3) x1 = Integer.parseInt(reader.readLine());", "3) it acts the same way as integer, there?s no real difference", "3) divides a number and shows the remainder", "3) Squareroot(x1);", "3) System.out.printline", "3) name = (reader.readLine()):", "3) ;", "3) can only hold words", "3) *", "3) <", "3) makes it easier for others to understand the code", "3) randit", "3) while works like an ?if?", "3) a description of the program", "3) ClassimportJava;", "3) The compiler is the same as a C++ compiler", "3) To state that the name of the method", "3) prints your program (without prompting)", "3) ==", "3) Default", "3) Runtime error", "3) No errors"};
     String[] Ds = {"4) Objective Oval Packets", "4) print.code", "4) ?", "4) num = floatparsefloat(reader.readLine())", "4) int num1:", "4) both A and B", "4) Functional", "4) System.out.print(??Hello??):", "4) x1 = parseInt(reader.readLine());", "4) it makes a whole value into a decimal", "4) shows the percentage of power being taken up during processing", "4) Math.sqrt(x1):", "4) System.out.printonaline", "4) name = (reader.readname());", "4) code end", "4) can hold numbers and words (but doesn?t hold the number?s numerical value)", "4) none of the above", "4) ?? ??", "4) doesn't make a difference", "4) random", "4) it allows the program to multi-task (ex. program calculates an answer WHILE it accepts another value)", "4) all of the above", "4) Java.io ImportClass", "4) Java is special", "4) To act as the entry point for the program", "4) shows your program and prompts the user to print", "4) &&", "4) Open", "4) Output of b = 1", "4) None of the above"};
       int [] answer = {3,2,1,3,1,2,1,3,3,1,3,2,2,1,3,4,3,1,3,2,1,4,1,2,4,2,2,2,1,3}; // answer key

                 int retry = 0;   
                 String retryy ;     
                 
while (retry < 2) { // retry loop
    JOptionPane.showMessageDialog(null,"Welcome to Qamar's Java Quiz \n"
                                    + "You will shortly be asked 10 questions\n"
                                    + "Please enter a value between 1 - 4 for your answer\n"
                                    + "After you finish the quiz you will be presented with your final score");
                                 
                int count = 0;
                String ans;
                float mark = 0;
                float percent = 0;
                int ans2 ;
                int [] flag = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};           
               
     
                while (count < 10) { // question loop
         
                Random r = new Random();
                int randint = r.nextInt(29); // array starts at 0 -> 29 which = 30
           
        while (flag [randint] >= 1)
            {
            randint = r.nextInt(29);
            flag [randint] = flag [randint];
        }
           
            ans = JOptionPane.showInputDialog("" + Qs[randint] + "\n"
            +"" + As[randint] + "\n"
            +"" + Bs[randint] + "\n" 
            +"" + Cs[randint] + "\n" 
            +"" + Ds[randint] + "\n" );
            ans2 = Integer.parseInt(ans);
           
            if (ans2 == answer[randint])
            {
                mark = mark+ 1;
            }
           
            flag [randint] = flag [randint] + 1;
            count = count + 1;
        } // end loop

percent = mark / count;
percent = percent * 100;
percent = Math.round (percent);
JOptionPane.showMessageDialog(null,"Your score is: " + mark + " out of " + count + " which is " + percent + "%");// diplays a pop-up that has the final information

            retryy = JOptionPane.showInputDialog("Would you like to play again? \n"
            + "1) Yes\n"
            + "2) No");
                             retry = Integer.parseInt(retryy);
                                   
//                              if (retry == 1)
//
//                                     {
//                                         JOptionPane.showMessageDialog(null,"Okay here we go again. ");
//                                     }
                                    if (retry == 2)
                                    {
                                        JOptionPane.showMessageDialog(null,"Thank you for playing. ");
                                    }
                                }// end retry loop
           } // end method
        } // end class
[/code]

Author:  Qamar [ Thu Nov 20, 2008 9:11 pm ]
Post subject:  Re: Making a quiz

hey i wrote this code a while ago... i thought i'd bring it back up to ask is this code OOP ??. or is it structural ?.. our compsci teacher had to leave for medical reason last year so i had to teach myself this.. and Barbarrosa said he wanted to see this code after... so yeah.

Author:  Tony [ Thu Nov 20, 2008 9:43 pm ]
Post subject:  Re: Making a quiz

Qamar @ Thu Nov 20, 2008 9:11 pm wrote:
is this code OOP ??. or is it structural ?

There is only one class and only one method. You get one guess to answer your own question Wink

Author:  Qamar [ Thu Nov 20, 2008 9:51 pm ]
Post subject:  Re: Making a quiz

i'm going to say.... no, haha
last year i had to self teach myself java.
how would i make this into object oriented ?

Author:  Barbarrosa [ Fri Nov 21, 2008 3:01 pm ]
Post subject:  Re: Making a quiz

code:

class Question{
       private String question;
       private Vector<String> answers;
       private int rightAns;
       public Question(String q){
              question = q;
              answers = new Vector<String>();
              rightAns = -1;
       }

       public String getQuestion(){
              return answer;
       }

       public String getAnswer(int i){
              return answers.get(i);
       }

       public String removeAnswer(int i){
              return answers.remove(i);
       }

       public int getNumAnswers(){
              return answers.size();
       }

       public void addAnswer(String s){
              answer.add(s);
       }

       public void setRightAnswer(int i) throws Exception{
              if(i<0 || i>answers.size()-1){
                     throw new Exception("Number not within bounds");
              }
              rightAns = i;
       }

       public boolean isRight(String s) throws Exception{
              if(rightAns == -1){
                     throw new Exception("Right answer not set");
              }
              if(s.equals(answers.get(rightAns)){
                     return true;
              }
              return false;
       }

       public boolean isRight(int i) throws Exception{
              if(rightAns == -1){
                     throw new Exception("Right answer not set");
              }
              if(rightAns == i){
                     return true;
              }
              return false;
       }
}

Author:  wtd [ Sat Nov 22, 2008 12:24 am ]
Post subject:  RE:Making a quiz

What's wrong with the following?

code:
       public boolean isRight(int i) throws Exception{
              if(rightAns == -1){
                     throw new Exception("Right answer not set");
              }
              if(rightAns == i){
                     return true;
              }
              return false;
       }

Author:  Barbarrosa [ Mon Nov 24, 2008 10:16 pm ]
Post subject:  Re: Making a quiz

Possibly the use of "right" instead of correct, but I don't see any other substantial reason. If we have a method accepting a number instead of a String, we reduce the work the computer will need to go through when computing whether the answer to the question is correct, depending on the input method. If Qamar had used a non-console GUI (which he did), he may have been able to save the computer a little trouble (putting aside the GUI).

Also, an object is intended to save the programmer work - putting the answer in the question works pretty well towards that goal.


: