// //////////////////////////////////////////////// java applet Quizzer//// by David Levinson, Amalgamated Conglomerated Programmers, Inc.// August 11, 1997 (updated FSF license Jan 8, 1999)//// Quizzer: An applet to read a question file question by question, word by word// and allow the user to "buzz" in when the user knows the answer// the user's answer is compared to the correct answer// points are awarded based on how early in the question a correct answer was achieved// the user may skip questions forward or backward// the user may search on any word in the index by calling up a WWW search engine//// contact the programmer:// email: dmlevins@uclink4.berkeley.edu// http://path.berkeley.edu/~dlevinson/Quizzer/Quizzer.html// (510) 848-3057// 1822 Francisco St. #11// Berkeley, CA 94703////This program is free software; // you can redistribute it and/or modify it // under the terms of the GNU General Public License // as published by the Free Software Foundation; // either version 2 of the License, or (at your option) any later version. //// This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or// FITNESS FOR A PARTICULAR PURPOSE. //// See the GNU General Public License for  more details. // You should have received a copy of the GNU General Public License // along with this program; // if not, write to the Free Software Foundation, Inc., // 675 Mass Ave, Cambridge, MA 02139, USA.// http://www.linux.org/info/gnu.html// //////////////////////////////////////////////// Identifiers of variables// a - textarea// b - button// bo - boolean// c - choice (pulldown menu)// f - float// i - integer// l - label// p - panel// s - string// t - textfield// u - URL//import java.awt.*;import java.io.DataInputStream;import java.io.BufferedInputStream;import java.io.IOException;import java.net.URL;import java.net.URLConnection;import java.net.MalformedURLException;// //////////////////////////////////////////////// create class Quizzer// //////////////////////////////////////////////public class Quizzer extends java.applet.Applet implements Runnable {      String[] sWord = new String[20000];      String[] sPunct = new String[20000];      String[] sPrepunct = new String[20000];      String sCurrentstr;      String sLongstr;      String[] sPunctmark = new String[500];      String[] sQbegin = new String[500];      String[] sAbegin = new String[500];      String sUserans;      String[] sTestans=new String[500];      String sTestansf;      String sTestansc;      String sTestansu;      String[] sFullans=new String[500];      String sScript;      String sScript2;      int iWordcount;      int iWordmax;      int iRelpos;       int iLastqword;      int iLastaword;      int i;      int j;      int iFilelength;      int iQmax;      int iQcount;      int iQcountprev;      int[] iQstart = new int[500];      int[] iAstart = new int[500];       int iPunctmax=0;      int iLenx=15;      int iQbeginmax=0;      int iAbeginmax=0;      float fNewpt = 0.0f;      float fTotpt = 0.0f;      URL theURL;      boolean[] boUax= new boolean[500];      boolean boAllcapsans;      boolean boLead=false;// Define general text fields available to whole program      TextField tUserans = new TextField("",20);      TextField tFeedback = new TextField("Feedback ",20);      TextField tNewpoints = new TextField("New Pts ",10);      TextField tTotalpoints = new TextField("Total Pts",10);      TextField tCurrentword = new TextField("",20);      TextField tSearchfield = new TextField("",20);      TextArea aTextarea = new TextArea(10,80);      Choice cSearch = new Choice();// //////////////////////////////////////////////// Begin init method, // read in file // parse into words & questions// //////////////////////////////////////////////  public void init() {// Identify location to open        String url = getParameter("filename");// If location is bad, catch errors    try { this.theURL = new URL(url); }    catch ( MalformedURLException e) {      System.out.println("Bad URL: " + theURL);    }// Initialize some variables regarding file input and output    URLConnection conn = null;    DataInputStream data = null;    String line;    StringBuffer buf = new StringBuffer();// try to open file denoted by "theURL"    try {       conn = this.theURL.openConnection();      conn.connect();      data = new DataInputStream(new BufferedInputStream(	     conn.getInputStream()));      while ((line = data.readLine()) != null) {         	buf.append(line + "\n");      } // make longstr the accumulation of the string buffer "buf"      sLongstr+=buf.toString();    }// catch IO Exceptions    catch (IOException e) {      System.out.println("IO Error:" + e.getMessage());    } // Initialize arrays           for (i = 0; i < 20000; i++) {          sWord[i]="";          sPunct[i]="";          sPrepunct[i]="";       }      iFilelength = sLongstr.length();      for (i = 0; i < 500; i++) {         iQstart[i]=iFilelength;         iAstart[i]=iFilelength;         sTestans[i]="";         sFullans[i]="";         boUax[i]=false;         sAbegin[i] = "";         sQbegin[i] = "";          sPunctmark[i] = "";        }// Initialize some variables               sTestansf="";               sTestansc="";               sTestansu="";       iWordcount=0;       sPunctmark[1]="!";       sPunctmark[2]=".";       sPunctmark[3]="?";       sPunctmark[4]=",";       sPunctmark[5]=";";       sPunctmark[6]=":";       sPunctmark[7]="(";             sPunctmark[8]=")"; // Define Tossup Strings       sQbegin[1]="<QUE>";// Define Answer Strings       sAbegin[1]="<ANS>";       for (i=1;i<500;i++) {         if (sAbegin[i] != "" ) { iAbeginmax++; }         if (sQbegin[i] != "" ) { iQbeginmax++; }         if (sPunctmark[i] != "" ){ iPunctmax++;}       }// Loop through longstr character by character, // parse into "words" denoted by spaces, punctuation// increment word counter     j=0;     for (i = 1; i < iFilelength; i++) {           sCurrentstr=sLongstr.substring(i,i+1);          if ( (sCurrentstr.equals(" ")  || sCurrentstr.equals("\n")) && ( i > j) ) {   // word string            iWordcount++;            iWordmax++;            sWord[iWordcount]=sLongstr.substring(j,i).trim();//            System.out.println(iWordcount + " " + sWord[iWordcount]);// parse trailing punctuation string from word string              int iWordlength;             iWordlength=sWord[iWordcount].length();             if (iWordlength>1) {               //                for (int iCharpos = 0; iCharpos < sWord[iWordcount].length() ; iCharpos++) {//                   if (iCharpos==0) {boLead=true;}//                   else {boLead=false;}//                   sCurrentstr=sWord[iWordcount].substring(iCharpos,iCharpos+1);                 sCurrentstr=sWord[iWordcount].substring(iWordlength-1,iWordlength);                 for (int k = 1 ; k < iPunctmax+1 ; k++) {                     if (sPunctmark[k].equals(sCurrentstr)) {            //                        if (boLead=true) {//                          //sWord[iWordcount]=sWord[iWordcount].substring(iCharpos,iWordlength).trim();//                           sPrepunct[iWordcount]+=sPunctmark[k];//                         }//                        else {                           sWord[iWordcount] = sWord[iWordcount].substring(0,iWordlength-1).trim();                           sPunct[iWordcount]=sPunctmark[k];//                         }                         k=iPunctmax+1;// close if sPunctmark                     }// close for iCharpos//                }// close for int k               }// close if iWordlength            }              j=i+1;// close if = " " \n          }// close for i = 1 to length       }// Loop through str[] array element by element// parse file into questions by identifying question & answer starting positions// test for the word "question" and the word "answer", identify their word number       iQcount=0;// Loop through words, find questions and answers       for (iWordcount = 1; iWordcount < iWordmax; iWordcount++) {           sCurrentstr=sWord[iWordcount];                         if (sCurrentstr.equalsIgnoreCase("<QUE>")) {                iQcount++;                iQmax++;                iQstart[iQcount]=iWordcount;           //                System.out.println("qcount qstart " + iQcount + sWord[iWordcount] + iWordcount);             }                                    if (sCurrentstr.equalsIgnoreCase("<ANS>")) {                boAllcapsans=false;                iAstart[iQcount]=iWordcount;           //                System.out.println("qcount astart " + iQcount + sWord[iWordcount] + iWordcount);              }           // initialize test answer           if (iAstart[iQcount]!=iFilelength) {              sFullans[iQcount]+=sWord[iWordcount]+sPunct[iWordcount]+" ";           }            if (iWordcount > iAstart[iQcount] ) {// First word after "<REQ>" = answer test              if (sWord[iWordcount].trim().equalsIgnoreCase("<REQ>"))                        {                 sTestansc="On";                       }              else if (sWord[iWordcount].trim().equalsIgnoreCase("</REQ>"))                        {                 sTestansc="";                       }               else if (sTestansc.equalsIgnoreCase("On") && sTestansf.equalsIgnoreCase(""))                        {                  sTestansf=sWord[iWordcount].trim();                       }              else if (sTestansc.equalsIgnoreCase("On") &! sTestansf.equalsIgnoreCase(""))                        {                  sTestansf+=" "+sWord[iWordcount].trim();                       }              }             if (iQcount!=iQcountprev) {               if (sTestansf != "") {sTestans[iQcount-1]=sTestansf;}               iQcountprev=iQcount;               sTestansf="";               sTestansc="";               sTestansu="";             }// close for iWordcount loop         }// Initialize layout manager            setLayout(new BorderLayout());           Button bBuzz = new Button("Buzz");      Button bPause = new Button("Pause");      Button bResume = new Button("Resume");      Button bSkip = new Button("Skip");      Button bPrevious = new Button("Previous");      Button bClear = new Button("Clear");      Button bBackword = new Button(" <-- ");      Button bForeword = new Button(" --> ");      Button bPlus = new Button("  +   ");      Button bReplace = new Button("Replace");      Button bSearch = new Button("Search");      Panel pBuzzpause = new Panel ();      pBuzzpause.setLayout(new BorderLayout());      pBuzzpause.add("West",bBuzz);      pBuzzpause.add("East",bPause);      Panel pAnswer = new Panel();      pAnswer.setLayout(new BorderLayout());      Label lUserans = new Label("Enter Your Answer:",Label.RIGHT);       pAnswer.add("North",lUserans);      pAnswer.add("Center",tUserans);      Panel pUsercontrol = new Panel();      pUsercontrol.setLayout(new BorderLayout());      pUsercontrol.add("West",bPrevious);      pUsercontrol.add("Center",bResume);      pUsercontrol.add("East",bSkip);      Panel pResponse = new Panel ();      pResponse.setLayout(new BorderLayout());      Label lResponse = new Label("         ",Label.CENTER);      pResponse.add("West",pBuzzpause);      pResponse.add("Center",pAnswer);      pResponse.add("East",pUsercontrol);      pResponse.add("South",lResponse);       Panel pArrow = new Panel();      pArrow.setLayout(new BorderLayout());      pArrow.add("West",bBackword);      pArrow.add("Center",tCurrentword);      pArrow.add("East",bForeword);      Panel pSetsearch = new Panel();      pSetsearch.setLayout(new BorderLayout());      pSetsearch.add("West",bPlus);      pSetsearch.add("East",bReplace);      Panel pLookup = new Panel();      pLookup.setLayout(new BorderLayout());      pLookup.add("West",pArrow);      pLookup.add("East",pSetsearch);      cSearch.addItem("AltaVista");      cSearch.addItem("Excite");      cSearch.addItem("Infoseek");      cSearch.addItem("Yahoo");      Panel pPickengine = new Panel();      pPickengine.setLayout(new BorderLayout());      Label lSearchfield = new Label("Search Field",Label.RIGHT);       pPickengine.add("West",lSearchfield);      pPickengine.add("Center",tSearchfield);      pPickengine.add("East",cSearch);      Panel pFindweb = new Panel();      pFindweb.setLayout(new BorderLayout());      pFindweb.add("West",bClear);      pFindweb.add("Center",pPickengine);      pFindweb.add("East",bSearch);      Panel pSouth = new Panel();      pSouth.setLayout(new BorderLayout());      pSouth.add("North",pResponse);      pSouth.add("Center",pLookup);      pSouth.add("South",pFindweb);      Panel pNorth = new Panel();      pNorth.setLayout(new BorderLayout());      pNorth.add("West",tNewpoints);      pNorth.add("Center",tFeedback);      pNorth.add("East",tTotalpoints);      add("North",pNorth);      add("Center",aTextarea);      add("South",pSouth);// close init  }// create  actions test    public boolean action(Event evt, Object arg) {      if (evt.target instanceof Button) {       controlBuzz((String)arg);       return true;      }       else if (evt.target instanceof TextField) {        controlAnscheck((String)arg);        return true;      }      else if (evt.target instanceof Choice) {        controlChoicecheck();        return true;      }      else return false;    }// create controlChoicecheck module to check selected search engine     void controlChoicecheck() {        String sEngine=cSearch.getSelectedItem();        if (sEngine == "") { sEngine="Yahoo";}        if (sEngine == "Altavista") {          sScript="http://altavista.digital.com/cgi-bin/query?pg=q&what=web&kl=xx&q=";          sScript2="";        }        else if (sEngine == "Excite") {          sScript="http://www.excite.com/search.gw?trace=a&search=";          sScript2="";        }       else if (sEngine == "Infoseek") {          sScript="http://guide-p.infoseek.com/Titles?qt=";          sScript2="&col=WW&sv=I2";        }        else if (sEngine == "Yahoo") {          sScript="http://search.yahoo.com/bin/search?p=";          sScript2="";        }     }// create controlAnscheck module to respond to text field answer    void controlAnscheck(String userans) {        runner.suspend();        sUserans=tUserans.getText().trim();// scoring module// feedback to user module          if (sUserans.equalsIgnoreCase(sTestans[iQcount])) {            fNewpt = 10.0f + 10.0f * ( 1.0f - ( (float)iWordcount - (float)iQstart[iQcount] ) / ( ( (float)iAstart[iQcount] - 1.0f ) - (float)iQstart[iQcount] ) );            tFeedback.setText("Yes: "+" *"+sTestans[iQcount]+"* " + sFullans[iQcount]);           }                   else {            fNewpt= -5.0f + -5.0f * ( 1.0f - ( (float)iWordcount - (float)iQstart[iQcount] ) / ( ( (float)iAstart[iQcount] - 1.0f ) - (float)iQstart[iQcount] ) );            if ( iWordcount > (iAstart[iQcount]-1) ) {              fNewpt=0.0f;            }            tFeedback.setText("No : " +" *"+sTestans[iQcount]+"* "+ sFullans[iQcount]);          }         if (boUax[iQcount] == true || iWordcount > iAstart[iQcount]) {            fNewpt=0.0f;         }         fTotpt+=fNewpt;         tNewpoints.setText("Pts " + (int)fNewpt);         tTotalpoints.setText("Tot " + (int)fTotpt);         tUserans.setText("");         boUax[iQcount]=true;         runner.resume();         iRelpos=0;       }// create controlBuzz module to respond to button actions    void controlBuzz(String bname) {      if (bname.equals("Buzz")) {        runner.suspend();        iRelpos=0;        tCurrentword.setText(sWord[iWordcount]);       }       else if (bname.equals("Resume")) {        runner.resume();       }       else if (bname.equals("Skip")) {        runner.suspend();        iRelpos=0;        if (iQcount >= iQmax) {          aTextarea.setText("End of File");        }        else {          iWordcount = iQstart[iQcount+1];          iQcount++;         iLastqword = iAstart[iQcount] - 1;         iLastaword = iQstart[iQcount+1] - 1;          aTextarea.setText("");          iLenx=15;        }        runner.resume();       }       else if (bname.equals("Previous")) {        runner.suspend();       iRelpos=0;        if (iQcount <= 1) {          aTextarea.setText("Beginning of File");        }        else if (iQcount > iQmax) {          aTextarea.setText("End of File");        }        else {         iWordcount = iQstart[iQcount-1];         iQcount--;         iLastqword = iAstart[iQcount] - 1;         iLastaword = iQstart[iQcount+1] - 1;         aTextarea.setText("");         iLenx=15;        }        runner.resume();       }       else if (bname.equals("Clear")) {        runner.suspend();        iRelpos=0;        tSearchfield.setText("");       }      else if (bname.equals("Pause")) {        runner.suspend();        iRelpos=0;        tCurrentword.setText(sWord[iWordcount]);       }       else if (bname.equals("Search")) {        runner.suspend();        controlChoicecheck();        URL uSearch=null;        String sSearch=sScript + tSearchfield.getText() + sScript2;        try { uSearch=new URL(sSearch);          }        catch (MalformedURLException e) {          System.out.println("Bad URL:" + uSearch);         }        getAppletContext().showDocument(uSearch);        getAppletContext().showStatus(sSearch);       }       else if (bname.equals(" <-- ")) {        runner.suspend();        iRelpos--;        tCurrentword.setText(sWord[iWordcount+iRelpos]);       }       else if (bname.equals(" --> ")) {        runner.suspend();        iRelpos++;        tCurrentword.setText(sWord[iWordcount+iRelpos]);       }       else if (bname.equals("  +   ")) {        runner.suspend();        tSearchfield.setText(tSearchfield.getText().trim() + "+" + tCurrentword.getText().trim());       }       else if (bname.equals("Replace")) {        runner.suspend();        tSearchfield.setText(tCurrentword.getText().trim());       }     }     Thread runner; // //////////////////////////////////////////////// start method calls runner// //////////////////////////////////////////////    public void start() {      if (runner == null) {        runner = new Thread(this);        runner.start();      }    }// //////////////////////////////////////////////// stop method stops runner// //////////////////////////////////////////////    public void stop() {      if (runner != null) {        runner.stop();        runner = null;      }    }// //////////////////////////////////////////////// run method implements write to screen thread// //////////////////////////////////////////////        public void run() {// loop through questions from 1 to qcount      for (iQcount = 1; iQcount <= iQmax; iQcount++) {         sCurrentstr="";         aTextarea.setText("");         iLastqword = iAstart[iQcount] - 1;         iLastaword = iQstart[iQcount+1] - 1;         iLenx=0;// loop through words in question iQcount             for (iWordcount = iQstart[iQcount]; iWordcount < iLastaword+1; iWordcount++) {        sCurrentstr=sWord[iWordcount]+sPunct[iWordcount]+" ";        aTextarea.appendText(sCurrentstr);        iLenx+=sCurrentstr.length();        pause(250);        if (iLenx>70) {            aTextarea.appendText("\n");            iLenx=0;         }               if (iWordcount == iLastqword || iWordcount == iLastaword ) {            aTextarea.appendText("\n");            iLenx=0;            pause(1500);         }     }       }  // close run method    }// create pause method     void pause (int time) {       try { Thread.sleep(time); }       catch (InterruptedException e) {}     }// close final}