+ All Categories
Home > Technology > Quiz report

Quiz report

Date post: 17-May-2015
Category:
Upload: carrie-hall
View: 1,016 times
Download: 3 times
Share this document with a friend
Description:
University project report to document a Java program which uses JSP pages to display and mark quiz questions stored in XML.
Popular Tags:
36
UNIVERSITY OF MANCHESTER COMP27010 Coursework 3 Carrie Louise Hall 7179881 April 24 th 2009 The aim of this report is to document a Java program which uses JSP to display and mark quiz questions.These quizzes are stored in XML format.
Transcript
Page 1: Quiz report

UNIVERSITY OF MANCHESTER

COMP27010 Coursework 3

Carrie Louise Hall 7179881

April 24th 2009

The aim of this report is to document a Java program which uses JSP to display and mark quiz questions.These quizzes are stored in XML format.

Page 2: Quiz report

Carrie Hall 7179881 - 1 -

Table of Contents

Description of Design ................................................................................................................................................................ ................. - 2 -

Loading the program............................................................................................................................................................................. - 2 -

Reading in the XML document .......................................................................................................................................................... - 2 -

Displaying the Quiz ................................................................................................................................................................ ................ - 3 -

Marking the Quiz................................................................................................................................................................ ..................... - 3 -

Completing the Quiz .............................................................................................................................................................................. - 3 -

Session Variables ................................................................................................................................................................ .................... - 3 -

Class Diagram................................................................................................................................................................ ................................ - 4 -

Introduction ......................................................................................................................................................................................... - 4 -

Diagram ................................................................................................................................................................ ................................. - 4 -

Hierarchical Task Analysis ................................................................................................................................................................ ...... - 5 -

Introduction ......................................................................................................................................................................................... - 5 -

Diagram ................................................................................................................................................................ ................................. - 5 -

Sequence Diagram ................................................................................................................................................................ ...................... - 5 -

Introduction ......................................................................................................................................................................................... - 5 -

Diagram ................................................................................................................................................................ ................................. - 5 -

Screenshots ................................................................................................................................................................ .................................... - 6 -

Step one ................................................................................................................................................................ ................................. - 6 -

Step two ................................................................................................................................................................ ................................. - 6 -

Step three .............................................................................................................................................................................................. - 7 -

Step four ................................................................................................................................................................ ................................ - 7 -

Step five ................................................................................................................................................................ ................................. - 9 -

Step six ................................................................................................................................................................ ................................ - 10 -

Works Cited ................................................................................................................................................................ ................................ - 11 -

Appendix ................................................................................................................................................................ ...................................... - 12 -

XML Original Quiz – Quiz 1 (People.xml) ................................................................................................................................... - 12 -

XML Result................................................................................................................................................................ .............................. - 13 -

XMLWriter.java .................................................................................................................................................................................... - 14 -

XMLReader.java ................................................................................................................................................................ ................... - 15 -

Quiz.java ................................................................................................................................................................ .................................. - 19 -

Question.java ................................................................................................................................................................ ......................... - 23 -

Answer.java ................................................................................................................................................................ ............................ - 24 -

Index.html ............................................................................................................................................................................................... - 26 -

Error.jsp................................................................................................................................................................ ................................... - 27 -

Success.jsp ................................................................................................................................................................ .............................. - 28 -

ShowQuiz.jsp ................................................................................................................................................................ ......................... - 29 -

MarkTest.jsp .......................................................................................................................................................................................... - 33 -

Page 3: Quiz report

Carrie Hall 7179881 - 2 -

Description of Design

Loading the program The initial page of the program is index.jsp. This file contains an input box for the user to enter their name. This name is used to store session variables in the program and also it is used in the creation of the XML documents to store the users’ answers. The index page also contains a drop down box which contains some predefined quizzes that the user can take. The value in the dropdown box is the filename of the XML document which contains that quiz. The title of the quiz is what is displayed to the user. The input box and drop down menu are part of a form element which redirects to the file showQuiz.jsp on submission.

As previously mentioned, the filename of the required quiz is passed in to showQuiz.jsp. Validation is done to ensure that the user entered a valid name (with valid being a non-empty string). If the name is invalid then the page redirects to the error.jsp page where it displays the error to the user. Once validation is complete the filename is sent to the XMLReader class.

Reading in the XML document The XMLReader class uses the Java built-in function newDocumentBuilder() in the DocumentBuilderFactory class. According to Sun Microsystems, this method “defines a factory API that enables applications to obtain a parser that produces DOM object trees from XML documents” (Sun Microsystems, 2004). Once this instance has been created, a recursive1

function is run to create the Quiz object. Firstly the method checks that the current element node is one of the following: test, question, answer. These are the only elements which should be in the XML document therefore if the method encounters an incorrect node the error count is increased and the file will not convert (a message will be displayed to the user on such an event). If the method encounters a test node it validates that the text node has an attribute called ‘name’ which must not be empty. A Quiz object is then created by passing in the quiz name. The test node should look like the XML snipped shown in Figure 1.

Figure 1

If a question node is encountered then the method validates that it has a ‘number’ attribute indicating the number of the question. A Question object is created and added to the Quiz object provided that the question number does not already exist in the Quiz. The question node should look like the XML snipped shown in Figure 2.

Figure 2

If an answer node is encountered then the method also validates that it has a ‘number’ attribute indicating the number of the answer, but also that it has a ‘type’ attribute. Validation is used to ensure that this attribute must be either ‘correct’ or ‘incorrect’ and a question can have only one ‘correct’ answer. The answer is linked to the question by storing the value of the current question, i.e. a question is found and every answer that is found after it is considered to be an answer of that question (until another question is reached). Again an Answer object is created and added to the test, passing in the answer, its number and type and the question number. This too is subject to validation to guarantee that each answer number is unique. Further validation is done on answers to make certain that a Question has one and only one correct answer. The answer node should look like the XML snipped shown in Figure 3.

1 Recursion: The ability of a program to call itself which also enables a program to define itself in terms of itself (Terry, 2001)

<test name=“General Knowledge”>

<question number=“1”> What is the capital of Italy? </question>

Page 4: Quiz report

Carrie Hall 7179881 - 3 -

Figure 3

Displaying the Quiz The Quiz object is returned to the showQuiz.jsp page where the function prints all questions and answer sets by using a loop. Each question is shown on the screen and radio buttons are used for the answers. Radio buttons enforce the user to select a correct answer. A common difficulty when using radio buttons is that a user can sometimes not select one which leads to null values. To overcome this, the method automatically selects the first item in each answer set. Hidden variables are used in the form to store important information about the quiz, namely the filename, quiz name, the total number of questions and the number of answers for each question. Once the user has selected all answers and press the submit button the page is redirected to MarkTest.jsp.

The Quiz uses CSS 2

Marking the Quiz

to style the page into an easy-to-read page.

At the MarkTest.jsp page the aforementioned hidden variables are used to loop through the questions and answers and get the items that the user selected. Each of these question and single answer sets are stored as an XML file named in the format shown in Figure 4 where quizname is the name of the quiz, person is the persons name, date is a timestamp to uniquely identify each quiz attempt and attempts is the number of attempts.

Figure 4

If the correct answer was not selected then it all questions except the one that they selected are added to a new Quiz which will be shown to the user. If this Quiz has any questions then the page will be redirected back to showQuiz.jsp.

Completing the Quiz Once the user has selected all the correct answers they are taken to the success.jsp page which informs them of how many attempts they took at the quiz which will be explained momentarily. The number of attempts affects the message that they receive on the success page.

Session Variables Session variables are used to store information that will be passed through each of the .jsp pages. A Quiz session holds the current Quiz which is how the quiz gets progressively smaller as the user selects incorrect answers. A session is also used to store the amount of times a user submits a quiz as previously discussed. These variables are reset once the user is redirected back to the homepage to choose another quiz to take.

2 CSS: Cascading Style Sheet. They are used to style HTML tags on a webpage.

<answer number=“1” type=“correct”> Rome </answer>

quizname_person_date_attempts.xml

Page 5: Quiz report

Carrie Hall 7179881 - 4 -

Class Diagram

Introduction Class diagrams are widely used in software development and “describes the types of objects in the system and the various kinds of static relationships that exist among them” (Fowler, 2004).

Key:

Class Name

Attributes

Methods

Diagram

Page 6: Quiz report

Carrie Hall 7179881 - 5 -

Hierarchical Task Analysis

Introduction Hierarchical task diagrams describe “how tasks are split into sub-tasks, their ordering and when they are performed” (Stevens, 2008). The structure of a hierarchical task diagrams usually consists of “a goal at the top, followed by sub-goals, unit tasks and artefacts. Sub-goals may be further sub-divided as required” (ACM, 2005). These goals are normally written from the perspective of the user.

Diagram

Sequence Diagram

Introduction This diagram shows the classes that will be called when the system is run.

Diagram

Page 7: Quiz report

Carrie Hall 7179881 - 6 -

Screenshots

Step one The page is loaded and a text field is shown to the user

Step two The user does not enter a name in the text field

Page 8: Quiz report

Carrie Hall 7179881 - 7 -

Step three There is a problem with the XML file. In this example, there is no correct answer for one of the questions.

Step four The user has entered a correct name and the XML file is valid so the quiz is shown (image on following page)

Page 9: Quiz report

Carrie Hall 7179881 - 8 -

Page 10: Quiz report

Carrie Hall 7179881 - 9 -

Step five The user has entered some correct and some incorrect answers so the quiz is redisplayed with the incorrect answers. Their original answer has been removed

Page 11: Quiz report

Carrie Hall 7179881 - 10 -

Step six After a few more attempts the quiz has been successfully completed. A different message is shown if the user had got more or less answers.

Page 12: Quiz report

Carrie Hall 7179881 - 11 -

Works Cited ACM. (2005, January/February). A Tale of Two Tutorials: A Cognitive Approach to Interactive System Design and Interaction Design Meets Agility. Interactions Magazine , pp. 49-51.

Fowler, M. (2004). UML Distilled. Addison-Wesley.

Stevens, R. (2008). Task Analysis. CS2341 Lecture Notes . Manchester: University Of Manchester.

Sun Microsystems. (2004, January 8). Class DocumentBuilderFactory. Retrieved April 01, 2009, from http://java.sun.com/j2se/1.5.0/docs/api/javax/xml/parsers/DocumentBuilderFactory.html

Terry, H. (2001, April 30). Glossary of Terms. Retrieved April 1, 2009, from PC AI Online: http://www.pcai.com/web/glossary/pcai_j_l_glossary.html

Page 13: Quiz report

Carrie Hall 7179881 - 12 -

Appendix This appendix contains the code for the program and the XML files that are produced.

XML Original Quiz – Quiz 1 (People.xml) This is an example of one (out of 3) of the original XML quizzes used in this program.

<?xml version="1.0" ?> <test name='People'> <question number='1'>Siddartha Gautama is </question> <answer number='1' type="correct">Founder of Buddhism</answer> <answer number='2' type="incorrect">Founder of Hinduism</answer> <answer number='3' type="incorrect">Founder of Islam</answer> <question number='2'>Socrates is </question> <answer number='1' type="incorrect">Egyptian Pharoah</answer> <answer number='2' type="incorrect">Enlightened Master</answer> <answer number='3' type="correct">Greek Philosopher</answer> <question number='3'>Herodotus is </question> <answer number='1' type="correct">"Father of History" wrote about Persian wars</answer> <answer number='2' type="incorrect">"Father of History" wrote about Punic wars</answer> <answer number='3' type="incorrect">"Father of History" wrote about Peloponesian</answer> <question number='4'>Emperor Xerxes is </question> <answer number='1' type="correct">Led battle of Thermopoleyes in the Persian Wars</answer> <answer number='2' type="incorrect">Led battle of Thermopoleyes in the Peloponesian War</answer> <answer number='3' type="incorrect"> Led battle of Thermopoleyes in the Punic Wars</answer> <question number='5'>Homer is </question> <answer number='1' type="incorrect">Wrote Medea</answer> <answer number='2' type="correct">Wrote the Illiad and the Odyssey</answer> <answer number='3' type="incorrect">Wrote poems about love and friendship</answer> </test>

Page 14: Quiz report

Carrie Hall 7179881 - 13 -

XML Result This is an example of the XML files that are produced when the user submits a quiz several times

Filename: General_Knowledge_Carrie L Hall_1240941105812 attempt1.xml <?xml version="1.0"?> <test name='General_Knowledge'> <question number='1'>What is the most common Element on Earth?</question> <answer number='1' type='incorrect'>Oxygen</answer> <question number='2'>How many miles high is Mount Everest (to nearest mile)?</question> <answer number='1' type='correct'>9 Miles</answer> <question number='3'>Which country features a maple leaf on its flag?</question> <answer number='1' type='incorrect'>France</answer> <question number='4'>What is the worlds most spoken language?</question> <answer number='1' type='correct'>Chinese (Mandarin)</answer> <question number='5'>What year did the Berlin Wall come down?</question> <answer number='1' type='incorrect'>1986</answer> </test>

Filename: General_Knowledge_Carrie L Hall_1240941105812 attempt2.xml <?xml version="1.0"?> <test name='General_Knowledge'> <question number='1'>What is the most common Element on Earth?</question> <answer number='2' type='correct'>Hydrogen</answer> <question number='3'>Which country features a maple leaf on its flag?</question> <answer number='2' type='incorrect'>Russia</answer> <question number='5'>What year did the Berlin Wall come down?</question> <answer number='2' type='incorrect'>1992</answer> </test>

Filename: General_Knowledge_Carrie L Hall_1240941105812 attempt3.xml <?xml version="1.0"?> <test name='General_Knowledge'> <question number='3'>Which country features a maple leaf on its flag?</question> <answer number='3' type='correct'>Canada</answer> <question number='5'>What year did the Berlin Wall come down?</question> <answer number='3' type='incorrect'>1979</answer> </test>

Page 15: Quiz report

Carrie Hall 7179881 - 14 -

XMLWriter.java

package xmlquizpackage; import java.io.*; public class XMLWriter { public XMLWriter(String outputFile, Quiz UserQuiz) { try { //open the file to write PrintStream os = new PrintStream(new FileOutputStream(new File(outputFile))); //header information os.println("<?xml version=\"1.0\"?>"); //'test' is the root element os.println("<test name='"+UserQuiz.getQuizName()+"' " + "attempts='"+UserQuiz.getQuizAttempts()+"'>"); //print the quiz os.print(UserQuiz.toXML()); //end root element os.println("</test>"); os.flush(); os.close(); } catch(Exception e) { System.out.println(e); } } }

Page 16: Quiz report

Carrie Hall 7179881 - 15 -

XMLReader.java

package xmlquizpackage; //imports import javax.xml.parsers.*; import java.io.IOException; import org.w3c.dom.*; import org.xml.sax.SAXException; public class XMLReader { Document dom; //structure of document Quiz q; //the Quiz to create from the XML document int questionNum; //question number int errors; //error count public XMLReader(String quizIn) { errors = 0; dom = parseXMLFile(quizIn); //makes DocumentBuilderFactory analyseElements(dom, ""); //recursive method /*one final check that the XML document is valid is made to ensure that all questions have a correct answer. It has already been validated that they dont have more than one*/ if (!q.checkCorrectAnswers()) { errors++; } } /** * * @return Quiz that has been created */ public Quiz getQuiz() { return q; } /** * Used to check if there were any errors with the XML document * @return int */ public int getErrors() { return errors; } /** * Private method to create a DocumentBuilderFactory * @param xmlfile * @return Document (stored as variable 'dom' */ private Document parseXMLFile(String xmlfile)

Page 17: Quiz report

Carrie Hall 7179881 - 16 -

{ DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); try { DocumentBuilder db = dbf.newDocumentBuilder(); dom = db.parse(xmlfile); return dom; } catch (ParserConfigurationException pce) { errors++; } catch (SAXException se) { errors++; } catch (IOException ioe) { errors++; } return null; } /** * recursive method which creates Quiz object * @param node at which element is on * @param indent */ void analyseElements(Node node, String indent) { String name = node.getNodeName(); //gets name NodeList children = node.getChildNodes(); //gets children NamedNodeMap attributes = node.getAttributes(); //gets attributes switch (node.getNodeType()) { case Node.DOCUMENT_NODE: analyse(children, indent + " "); break; case Node.ELEMENT_NODE: if (name.equals("test")) //root element { //checks if it is missing attribute 'name' if (attributes.getNamedItem("name") != null) { try { //gets value of name attribute q = new Quiz(attributes.getNamedItem("name") .getNodeValue().toString()); //recursion analyse(children, indent + " "); } catch (DOMException e) //no value for name attribute {

Page 18: Quiz report

Carrie Hall 7179881 - 17 -

errors++; } } else //no attribute for name { errors++; } } else if (name.equals("question")) //question node { if (children.item(0) != null) //must have a text node { try { //get question info String question= children.item(0).getNodeValue().trim(); String number = attributes.getNamedItem("number") .getNodeValue(); //stores the question number so whatever answer nodes //follow this get added to this question questionNum = Integer.parseInt(number); //if question number is unique if (!q.addQuestion(questionNum, question)) { errors++; } analyse(children, indent + " "); } catch (DOMException e) { errors++; } catch (NumberFormatException n) { errors++; } } else //missing value for question { errors++; } } else if (name.equals("answer")) //answer node { if (children.item(0) != null) //must have a text node { try { //get answer details String answer = children.item(0).getNodeValue().trim(); String ansNum = attributes.getNamedItem("number").getNodeValue(); int answerNum = Integer.parseInt(ansNum); String type = attributes.getNamedItem("type").getNodeValue(); /*checks if answer number has not already been written and that only one correct answer is found*/ if (!q.addAnswer(questionNum, answerNum, answer, type))

Page 19: Quiz report

Carrie Hall 7179881 - 18 -

{ errors++; } } catch (DOMException e) { errors++; } catch (NumberFormatException n) { errors++; } analyse(children, indent + " "); } else //incorrect xml { errors++; } } else //incorrect xml { errors++; } break; default: break; } } /* Recursive method to read the XML file */ public void analyse(NodeList children, String indent) { for (int i = 0; i < children.getLength(); i++) { analyseElements(children.item(i), indent); } } }

Page 20: Quiz report

Carrie Hall 7179881 - 19 -

Quiz.java package xmlquizpackage; //imports import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; public class Quiz { String name; //stores the name of the quiz ArrayList<Question> questions; //stores the questions ArrayList<Answer> answers; //stores all answers /** MAIN METHOD. This class instantiates the ArrayLists and names the quiz according to the name of the file specified in the XML e.g. <test name="Java Quiz"> would call the quiz "Java Quiz" */ public Quiz(String nameIn) { questions = new ArrayList<Question>(); answers = new ArrayList<Answer>(); name = nameIn; } /** * Adds a question to the quiz * @param: question number * question */ public boolean addQuestion(int questionNoIn,String questionIn) { //loops through all questions Iterator i = questions.iterator(); while (i.hasNext()) { Question q = (Question) i.next(); //typecasts //if the question number is already in the list if(q.getQuestionNo()==questionNoIn) { return false; } } return questions.add(new Question(questionNoIn, questionIn)); } /** * Adds an answer to the quiz * @param: question number * answer number * answer * type (correct || incorrect) */ public boolean addAnswer(int questionNoIn,int answerNoIn,String answerIn, String typeIn) { //checks that it is of correct type if (!typeIn.equals("correct")) { if (!typeIn.equals("incorrect")) {

Page 21: Quiz report

Carrie Hall 7179881 - 20 -

return false; } } //loops through all answers Iterator i = getAnswers(questionNoIn).iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //typecasts //if the answer number is already in the list if(a.getAnswerNo()==answerNoIn) { return false; } /*If the XML file has two answers which it has labelled correct then an error should be shown*/ if (typeIn.equals("correct")) { if (a.getType().equals(typeIn)) { return false; } } } return answers.add(new Answer(questionNoIn,answerNoIn,answerIn,typeIn)); } /** * * @return ArrayList of questions belonging to this quiz */ public ArrayList<Question> getQuestions() { return questions; } /** * returns the quiz name * @return String (quiz name) */ public String getQuizName() { return name; } /** * Returns all answers belonging to a particular question * @param questionNo * @return ArrayList of questions belonging to this quiz */ public ArrayList<Answer> getAnswers(int questionNo) { //temp array to store certain variables from the "answers" ArrayList ArrayList<Answer> temp = new ArrayList<Answer>(); Iterator i = answers.iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //converts object to Answer if (a.getQuestionNo()==questionNo) //if it belongs to required q { temp.add(a); //adds to temp arrayList

Page 22: Quiz report

Carrie Hall 7179881 - 21 -

} } /*The list is then sorted using the Answer class method "compareTo()" * It sorts them based on their unique answer ID. This is so that the * order that the answers appear can be changed by changing the XML file * thus ensuring that correct answers can appear in "random" places. */ Collections.sort(temp); return temp; } /** * Returns the correct answer of a particular question * @param questionNo * @return String answer */ public int getCorrectAnswer(int questionNo) { Iterator i = answers.iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //converts object to Answer if (a.getQuestionNo()==questionNo) //if it belongs to required q { if (a.getType().equals("correct")) { return a.getAnswerNo(); } } } return -1; //will never be returned due to validation ensuring that //all questions have an answer } /** * Returns the correct answer of a particular question * @param questionNo * @return String answer */ public Answer getAnswerByNumber(int ansNum) { Iterator i = answers.iterator(); while (i.hasNext()) { Answer a = (Answer) i.next(); //converts object to Answer if (a.getAnswerNo()==ansNum) //if it belongs to required q { if (a.getType().equals("correct")) { return a; } } } return null; }

/*** Similiar to toString() method. * @return XML String */

Page 23: Quiz report

Carrie Hall 7179881 - 22 -

public String toXML() { String xml = ""; for (int i=0;i<getQuestions().size();i++) { Question q = getQuestions().get(i); //the XML question wrapper xml+="\t<question number='" + q.getQuestionNo() + "'>"; //the question itself xml+= q.getQuestion(); //end of question xml+="</question>\r"; //loops through answers for (int j=0;j<getAnswers(q.getQuestionNo()).size();j++) { Answer a = getAnswers(q.getQuestionNo()).get(j); //print answer xml+="\t\t<answer number='"+a.getAnswerNo()+"' type='"+a.getType()+"'>"; xml+= a.getAnswer(); xml+="</answer>\r"; } } return xml; //return full string } /** * Checks that at a correct answer is given for each question. Further * validation has been done to ensure that no more than 1 correct answer * can be given * @return boolean */ public boolean checkCorrectAnswers() { Iterator i = questions.iterator(); //loops through questions while (i.hasNext()) { boolean found = false; Question q = (Question) i.next(); //converts object to Answer Iterator j = this.getAnswers(q.getQuestionNo()).iterator(); while (j.hasNext()) { Answer a = (Answer) j.next(); //converts object to Answer if (a.getType().equals("correct")) { found = true; } } if (!found) { return false; //no correct answer } } return true; //not returned false so must be true } }

Page 24: Quiz report

Carrie Hall 7179881 - 23 -

Question.java

package xmlquizpackage; /** * Question class */ public class Question { int questionNo; String question; public Question(int questionNoIn,String questionIn) { questionNo = questionNoIn; question = questionIn; } public void editQuestion(String questionIn) { question = questionIn; } public void editQuestionNo(int questionNoIn) { questionNo = questionNoIn; } public int getQuestionNo() { return questionNo; } public String getQuestion() { return question; } }

Page 25: Quiz report

Carrie Hall 7179881 - 24 -

Answer.java

package xmlquizpackage; /*This class implements comparable because the answers are ordered by their answer number*/ public class Answer implements Comparable<Answer> { int questionNo; //question to which the answer belongs int answerNo; //orders the answers String answer; String type; //either "correct" OR "incorrect" public Answer(int questionIn,int answerNoIn,String answerIn,String typeIn) { questionNo = questionIn; answer = answerIn; answerNo = answerNoIn; type = typeIn; } public int getQuestionNo() { return questionNo; }

public int getAnswerNo() { return answerNo; }

public String getAnswer() { return answer; }

public String getType() { return type; }

public void editAnswer(String answerIn) { answer = answerIn; }

public void changeAnswerNumber(int answerNoIn) { answerNo = answerNoIn; }

Page 26: Quiz report

Carrie Hall 7179881 - 25 -

public void changeType(String typeIn) { type = typeIn; } /*The method which allows two answers to be compared*/ public int compareTo(Answer ans) { final int BEFORE = -1; final int EQUAL = 0; final int AFTER = 1; if (this.getAnswerNo() == ans.getAnswerNo()) { return EQUAL; } if (this.getAnswerNo() < ans.getAnswerNo()) { return BEFORE; } if (this.getAnswerNo() > ans.getAnswerNo()) { return AFTER; } assert this.equals(ans) : "compareTo inconsistent with equals."; return EQUAL; } }

Page 27: Quiz report

Carrie Hall 7179881 - 26 -

Index.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <link href="http://www.carriehall.co.uk/java/style.css" rel="stylesheet" type="text/css" /> <title>XML Quiz</title> <body> <h1>XML Quiz</h1> <form id="mainform" name="doForm" action="showQuiz.jsp" method="POST"> <table> <tr><td><input type="hidden" name="Action" value="Page" /> Please enter your name:</td> <td> <input type="text" name="person" value="" size="20" /></td> </tr> <tr><td>Please choose a quiz:</td><td> <select name="quiz"> <option value="generalknowledge.xml" selected>General Knowledge 1</option> <option value="generalknowledge2.xml" >General Knowledge 2</option> <option value="people.xml" >People</option> </select></td></tr> <tr><td colspan="2" align="right"><input type="submit" value="Go!" name="do" /></td></tr> </table> </form> </body> </html>

Page 28: Quiz report

Carrie Hall 7179881 - 27 -

Error.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> <% /* * This page gets displayed when an error occurs. */ //gets the session parameter containing the error message(s) String error = (String) session.getAttribute("error"); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>XML Quiz</title> </head> <body> <h1>Error</h1> <p>The following error occured:</p> <%= error %> <p><a href="index.html">Click here</a> to go to the main page</p> </body> </html>

Page 29: Quiz report

Carrie Hall 7179881 - 28 -

Success.jsp <!-- page imports ---> <%@page import="xmlquizpackage.*" %> <%@page contentType="text/html" pageEncoding="UTF-8"%> <% /* This page gets called when the user has completed the quiz */ String person = ""; String message = ""; int attempts = 0; if (session.getAttribute("person")!=null) { person = (String) session.getAttribute("person"); } if (session.getAttribute("attempts")!=null) { attempts = (Integer.parseInt(session.getAttribute("attempts").toString())); } if (attempts==1) { message+= " attempt. Well done!"; } else if (attempts>1 && attempts<4) { message+= " attempts. Nearly there!"; } else if (attempts<=4 && attempts<10) { message+= " attempts. Try a little harder next time!"; } else if (attempts>=10) { message+= " attempts. You have made history with this abysmal test!"; } %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>XML Quiz</title> </head> <body> <h1>Congratulations <%= person %>!</h1> <p>You completed the test in <%= attempts + message %> </p> <p><a href="index.html">Click here</a> to go back to the home page to attempt another quiz</p> </body> </html>

Page 30: Quiz report

Carrie Hall 7179881 - 29 -

ShowQuiz.jsp <!-- page imports --> <%@page import="java.util.Iterator" %> <%@page import="java.util.Iterator" %> <%@page import="xmlquizpackage.*" %> <!-- imports the classes --> <%@page contentType="text/html" pageEncoding="UTF-8"%> <%! /* method to redirect to the error page*/ public void doError(HttpServletResponse res,HttpSession sess,String errorMsg) {

try {

sess.setAttribute("error", errorMsg); res.sendRedirect("error.jsp");

} catch (Exception e) { }

} %> <% /* Main method. This is the page that displays quizzes to the user. It can be * called from index.html where it passes in the persons name and the quiz they * choose to take. It can also be called from the MarkTest.jsp page to redisplay * tests that have incorrect answers. */ //variables int errors = 0; //error count String errorMsg = ""; //error message String quiz = ""; //quiz filename (from dropdown) String person = ""; //persons name int attempts = 0; //number of attempts at test Quiz uQuiz = null; //Quiz object int qcount = 0; //to store the count of questions int maxNoOfAnswers = 0; //to store the maximum number of answers /* If request.getParameter("person") returns a result then it * must be a request from the 1st page. * Need to get the name of the person and the quiz, read in that quiz from XML * and turn it into a Quiz object to display. Only the first page has an */ if (request.getParameter("person")!=null) {

/*In case the person has done a test before and is choosing to do a second, the session attributes must be reset*/ session.setAttribute("attempts", 1); session.setAttribute("Quiz", null); session.setAttribute("person", null); //gets the persons name and removes whitespace person = request.getParameter("person").toString().trim(); if (person.equals(""))//if the person didn't enter a name {

errorMsg+="Please enter a valid name<br />"; //writes error message errors++; //increases error count

} else //correct name entered

Page 31: Quiz report

Carrie Hall 7179881 - 30 -

{ //gets the information sent from the initial form quiz = request.getParameter("quiz"); //dropdown box of quizzes person = request.getParameter("person"); //persons name attempts = 1; XMLReader x = new XMLReader(quiz); //reads the xml file if (x.getErrors()==0) //no errors occured with reading the xml file { uQuiz = x.getQuiz(); //saves the xml quiz } else //errors occurred { errorMsg+="Incorrect XML file<br />"; //writes error message errors++; //increases error count }

} } /*If there is no request.getParameter for "person" then the page will have been * called from the marktest page (ie its a resubmission of the quiz. This * Quiz is saved as a session variable and must be retrieved in order to show it * to the user */ else {

//gets the current number of attempts attempts = Integer.parseInt(session.getAttribute("attempts").toString()); //saves the session Quiz as uQuiz //this is the quiz that has reduced values uQuiz = (Quiz) session.getAttribute("Quiz"); //gets the persons name from the session person = (String) session.getAttribute("person"); //gets the filename quiz = (String) session.getAttribute("filename");

} if (errors>0) //errors occured {

doError(response,session,errorMsg); //call method to redirect } else //no errors so print the html {

//makes an iterator to loop through the questions in the quiz Iterator i = uQuiz.getQuestions().iterator();

%> <html> <head> <title>XML Quiz</title> </head> <body> <h1><%= uQuiz.getQuizName()%></h1> <!--Prints the name of the quiz --> <!--Prints the number of attempts --> <p>This is attempt number <%= attempts %> </p> <!-- begin form --> <form name='quiz' action='MarkTest.jsp'> <!-- hidden values to store important information --> <input type='hidden' name='person' value='<%= person%>' /> <input type='hidden' name='quizname' value='<%= uQuiz.getQuizName()%>'/>

Page 32: Quiz report

Carrie Hall 7179881 - 31 -

<input type='hidden' name='filename' value='<%= quiz %>' /> <% while (i.hasNext()) //while there are questions {

Question question = (Question) i.next(); //get question int QuestionNumber = question.getQuestionNo(); //get question no %> <!-- hidden question details --> <input type='hidden' name='questionNo<%=qcount%>' value='<%= QuestionNumber%>'/> <input type='hidden' name='questionVal<%=qcount%>' value='<%= question.getQuestion()%>' /> <!-- prints question --> <h5><%= QuestionNumber + ". " + question.getQuestion()%></h5> <% //iterates through answers of that question Iterator j = uQuiz.getAnswers(question.getQuestionNo()).iterator(); /*tempcount is used to find the maximum number of answers that a question can have*/ int tempcount = 0; while (j.hasNext())//while there are answers {

Answer answer = (Answer) j.next(); //get answer int AnswerNumber = answer.getAnswerNo(); //get answer number String answerString = answer.getAnswer();//get answer String %> <!-- shows answers as radio buttons --> <input name='a<%=qcount%>' id='a<%= qcount%>' type='radio' value='<%= AnswerNumber%>' <% /*In order to ensure that the user does not forget to select an answer, the first item in each select box will be selected. */ if (tempcount==0) { %> checked <% } %> ></input><!-- end of input --> <!-- label for the answer --> <label for='a<%= qcount%>'> <%= answerString%> </label> <br /> <% tempcount++; //increase tempcount

} //end of while j.hasnext() //if tempcount > current maxNoOfAnswers then store as maxNoOfAnswers if (tempcount > maxNoOfAnswers) {

maxNoOfAnswers = tempcount; } qcount++; //increase number of questions

} //end while i.hasnext() loop %> <!--hidden values to store max num of answers and # of questions--> <input type='hidden' name='anscount' value='<%= maxNoOfAnswers%>'/> <input type='hidden' name='qcount' value='<%= qcount%>' />

Page 33: Quiz report

Carrie Hall 7179881 - 32 -

<br /> <!-- submit button --> <input type='submit' name='submit' value='Submit' /> </form> <!-- end form --> </body> </html>

<% } //end if statement %>

Page 34: Quiz report

Carrie Hall 7179881 - 33 -

MarkTest.jsp <!-- page imports --> <%@page import="java.util.Iterator" %> <%@page import="java.util.Enumeration" %> <%@page import="java.util.Date" %> <%@page import="java.util.Calendar" %> <%@page import="xmlquizpackage.*" %> <%! /* method to redirect to the error page*/ public void doError(HttpServletResponse res,HttpSession sess,String errorMsg) {

try {

sess.setAttribute("error", errorMsg); res.sendRedirect("error.jsp");

} catch (Exception e) { }

} %> <% //variables int qcount = 0; //stores the number of questions Quiz realQuiz = null; //stores the full quiz Quiz temp = null; //stores the resubmitted quiz Quiz userQuizToSave = null; //stores the users answers String errorMsg = ""; //stores an error message String date; //stores a date //gets the filename and person name passed in through hidden variables String person = request.getParameter("person"); //persons name String filename = request.getParameter("filename"); //file name if (session.getAttribute("attempts")==null) //if this is the first attempt {

session.setAttribute("attempts", 1); //increase to two attempts } if (session.getAttribute("person")==null) //if it's not been set already {

session.setAttribute("person", person); //sets person session } if (session.getAttribute("date")==null) //if this is the first attempt {

date = "" + Calendar.getInstance().getTimeInMillis(); session.setAttribute("date", date); //increase to two attempts

} else //increase by one {

date = session.getAttribute("date").toString(); } String quiz = request.getParameter("quizname"); /*The system tries to read an XML file which is created when a user submits a test and it is incorrect. If a file exists then realQuiz is overwritten with the other quiz. This allows the test to get progressively smaller as the quiz is resubmitted*/ if (session.getAttribute("Quiz")!=null) {

realQuiz = (Quiz) session.getAttribute("Quiz"); } else

Page 35: Quiz report

Carrie Hall 7179881 - 34 -

{ XMLReader x = new XMLReader(filename); realQuiz = x.getQuiz();

} try {

//gets the total number of questions. qcount = Integer.parseInt(request.getParameter("qcount"));

} catch (NumberFormatException e) {

errorMsg += "Problem finding the number of questions<br />"; doError(response,session,errorMsg); //call method to redirect

} if (!quiz.equals("")) {

//makes a new quiz to store the incorrect answers temp = new Quiz(quiz); //makes a new quiz to store the answers that the user chose userQuizToSave = new Quiz(quiz);

} else {

errorMsg += "Problem finding the number of questions<br />"; doError(response,session,errorMsg); //call method to redirect

} for (int i = 0; i < qcount; i++) //loop through all questions {

//get question details int questionNo = Integer.parseInt(request.getParameter("questionNo" + i)); String question = request.getParameter("questionVal" + i); //stores a boolean to determine if answer is correct or not boolean correctAns = true; //get answer number selected by the user int answerNo = Integer.parseInt(request.getParameter("a" + i)); //the user entered the wrong answer so need to redisplay if (realQuiz.getCorrectAnswer(questionNo) != answerNo) {

correctAns = false; } if (!correctAns) //the user entered the wrong answer {

//save question to new test to redisplay temp.addQuestion(questionNo, question); //loop through answers for this question for (int k = 0; k < realQuiz.getAnswers(questionNo).size(); k++) {

//get answer details int tempAnsNum = realQuiz.getAnswers(questionNo).get(k).getAnswerNo(); String tempAns = realQuiz.getAnswers(questionNo).get(k).getAnswer(); String tempType = realQuiz.getAnswers(questionNo).get(k).getType(); /* The user will not be shown their incorrect answer and so it should not be added to the new Quiz */ if (tempAnsNum != answerNo) {

//adds the rest of the answers temp.addAnswer(questionNo, tempAnsNum, tempAns, tempType);

} }

Page 36: Quiz report

Carrie Hall 7179881 - 35 -

} /*The answers to every question will be stored as an XML file*/ userQuizToSave.addQuestion(questionNo, question); //Only the answer number that the user submitted is known, so a loop through //all answers for the question is needed to find the rest of the details for (int k = 0; k < realQuiz.getAnswers(questionNo).size(); k++) {

//get answer details int tempAnsNum = realQuiz.getAnswers(questionNo).get(k).getAnswerNo(); String tempAns = realQuiz.getAnswers(questionNo).get(k).getAnswer(); String tempType = realQuiz.getAnswers(questionNo).get(k).getType(); /* adds to user test */ if (tempAnsNum == answerNo) {

//adds the answer userQuizToSave.addAnswer(questionNo, tempAnsNum, tempAns, tempType);

} }

} /*The quiz has been marked and two tests have been made, one contains all the incorrect questions with all answers other than the submitted answer, and the other contains each question and answer the user gave.*/ if (temp.getQuestions().size() > 0) //the user has made mistakes {

if (session.getAttribute("attempts")==null) //if this is the first attempt {

session.setAttribute("attempts", 2); //increase to two attempts } else //increase by one {

session.setAttribute("attempts", 1+(Integer.parseInt(session.getAttribute("attempts").toString())));

} //writes an XML file with the users results. the file name is the quizname //and the persons name. To ensure uniqueness, a timestamp is also saved new XMLWriter(quiz + "_" + person + "_" + date + ".xml", userQuizToSave); session.setAttribute("Quiz", temp); session.setAttribute("filename", filename); //redirects to display the quiz again response.sendRedirect("showQuiz.jsp");

} else //successful test {

//redirects to display a success message response.sendRedirect("success.jsp");

} %>


Recommended