Featured Code

Here is the entire code for the Java Assignemtn where I have to create a java based quiz with special effects. The special features I added was to have an external log file of all the user's points and an external question modifier.

Main Class

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package assignment.pkg1.p1;

 

import static assignment.pkg1.p1.Method.QuestionPath;

import java.io.BufferedReader;

import java.io.File;

import java.io.FileReader;

import java.util.*;

import java.util.regex.*;

import javax.swing.JOptionPane;

/**

 *

 * @author francisyzy

 */

public class Main {

    public static void main(String[] args) throws Exception {

        long startTime = System.currentTimeMillis();//Time taken

        Method Main = new Method();

        Main.Question(); //ensure that there is a question set available

        int logQuestionSet;

        if(Main.QuestionList()==1)

            logQuestionSet = Main.QuestionSelect(1);

        else

            logQuestionSet = Main.QuestionSelect(Main.getUserInput(0, Main.QuestionList(), "Choose a question track by inputing an interger.\nThere are "+Main.QuestionList()+" questions tracks to choose from"));

        FileReader file = new FileReader(QuestionPath);//to allow message to be read for welcome message

        BufferedReader reader = new BufferedReader(file);

        Main.StartSound();//Sounds

        //Welcome Message

        Main.Message("Welcome to Quiz\nCurrently loaded quiz question is "+reader.readLine()+"\nPress cancel to exit quiz");

        //get Username for logs

        String Username =  JOptionPane.showInputDialog(null,"Enter your username for logs","Username",JOptionPane.QUESTION_MESSAGE);

        if("".equals(Username))

            Username = "User";

        if(Username == null)

            Username = "User";

        //initialise all the values such as amount of question and answers

        int Qcount=Main.getCount("Q:");

        int Lcount=Main.getLineCount();

        int Acount=Main.getCount("A:");

        int ACount=Acount/Qcount;

        //String[] Question = Main.getQuestions(Lcount, Qcount);//leagacy single array question

        //System.out.println(Lcount+"Line count");//debug

        //System.out.println(ACount+"Answer Count");//debug

        //System.out.println(Arrays.toString(Question));

        String[][] QuestionA = Main.getTXTinput(Lcount, Qcount, ACount);

        Main.Score(Qcount);//initialise the amount of question//leagacy single array question

        //Random generator

        Integer[] Rand = new Integer[Qcount];

        for (int i = 0; i < Rand.length; i++) {

            Rand[i] = i;

        }

        Collections.shuffle(Arrays.asList(Rand));

        //System.out.println(Rand[0]);//Debug testing random numbers

        String Question="";

        //TODO 2d array read// done

        for(int Q=0;Q<Qcount;Q++){

            int Qn=Q+1;

            boolean correct=false;

            int Qnn = Rand[Q];

            Question = QuestionA[Qnn][0]+"\n";

            for(int A=2;A<QuestionA[0].length;A++){

                Question+= QuestionA[Qnn][A]+"\n";

            }

            do{

                Main.QuestinStartSound();

                

                int Answer = Main.getUserInput(Qn, ACount, Question);

                if(Answer == Main.intParse(QuestionA[Qnn][1])){

                    Main.CorrectSound();

                    Main.Message("Correct");

                    correct=true;

                }else{

                    Main.WrongSound();

                    Main.Message("Wrong, answer is "+Main.intParse(QuestionA[Qnn][1]));

                    Main.Score(Qn, false);

                }

            }while(correct==false);

        }

        

        String Score = Main.returnScore(Qcount);

        

        if(Score.toLowerCase().contains("0/".toLowerCase()))

            Main.ZeroMarksSound();

        if(Score.toLowerCase().contains("3/".toLowerCase()))

            Main.ThreeMarksSound();

        

        Main.Message("You Scored "+Main.returnScore(Qcount));

        

        //log results

        Calendar calendar = new GregorianCalendar();

        Main.Logs(Username+" Scored "+Main.returnScore(Qcount)+" on "+calendar.getTime()+" for question set "+logQuestionSet);

        //find the user time taken

        double estimatedTime = (System.currentTimeMillis() - startTime)/1000;

        Main.Message("time taken="+estimatedTime+"s");

        int getLineCountLogg = Main.getLineCountLogg();

        int ShowLogs = JOptionPane.showConfirmDialog(null,"Do you want to see previous score?");

        int countLog=Main.getLineCountLog("set "+logQuestionSet);

        String[] Log= Main.getLogs("set "+logQuestionSet, getLineCountLogg, countLog);

        String LOG = "";

        for(int i=0;i<Log.length;i++)

            LOG+=Log[i]+"\n";

        if(ShowLogs==0){

            Main.Message(LOG);

            //System.out.println(Arrays.toString(Main.getLogs("set "+logQuestionSet, getLineCountLogg, countLog)));//debug purpose

        }

    }

}

 

Method Class

/*

 * To change this license header, choose License Headers in Project Properties.

 * To change this template file, choose Tools | Templates

 * and open the template in the editor.

 */

package assignment.pkg1.p1;

import javax.swing.JOptionPane;

import java.io.*; //use this

import java.util.Arrays;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

import sun.audio.*;

/**

 *

 * @author francisyzy

 */

public class Method {

    private int Score=0;

    private int Record=0;

    public static String QuestionPath="";

   

    public Method(){}

    

    //Sounds from https://www.reddit.com/r/montageparodies/comments/2o87hj/ultimate_mlg_starter_pack_1gb_of_edgy_content/

    

    public void StartSound()throws Exception{

        InputStream in = new FileInputStream(new File("Sound/Starting Sound.wav"));

        AudioStream as = new AudioStream(in);  

        AudioPlayer.player.start(as);

    }

    

    public void CorrectSound()throws Exception{

        InputStream in = new FileInputStream("Sound/Ding.wav");

        AudioStream as = new AudioStream(in);  

        AudioPlayer.player.start(as);

    }

    

    public void WrongSound()throws Exception{

        InputStream in = new FileInputStream("Sound/Explosion 00.wav");

        AudioStream as = new AudioStream(in);  

        AudioPlayer.player.start(as);

    }

    

    public void QuestinStartSound()throws Exception{

        InputStream in = new FileInputStream("Sound/Baaaaaaaassss.wav");

        AudioStream as = new AudioStream(in);  

        AudioPlayer.player.start(as);

    }

    

    public void ZeroMarksSound()throws Exception{

        InputStream in = new FileInputStream("Sound/2SED4AIRHORN.wav");

        AudioStream as = new AudioStream(in);  

        AudioPlayer.player.start(as);

    }

    

    public void ThreeMarksSound()throws Exception{

        InputStream in = new FileInputStream("Sound/Oh_Baby_A_Triple.wav");

        AudioStream as = new AudioStream(in);  

        AudioPlayer.player.start(as);

    }

    

    public int getUserInput(int Q, int ACount, String Qn){ //int Q is the question number

        int toReturn=0;

        boolean done=false;

        boolean tooHigh=false;

        do{

            do{

                while(done==false){

                    if(tooHigh == true){

                        Message("Please enter an answer ≤ "+ACount);

                    }

                    String toParse = JOptionPane.showInputDialog(null,Qn,"Q"+Q,JOptionPane.QUESTION_MESSAGE);

                    if(toParse != null){

                        try {

                           toReturn = Integer.parseInt(toParse);

                           done=true;

                        } 

                        catch (NumberFormatException e) {

                           Message(e.getMessage()+" is not a number");

                        }

                    }

                    else {

                            System.exit(0);

                    }

                }

                done=false;

                tooHigh = true;

            }while(toReturn>ACount);//to ensure value is < ACount

            return toReturn;

        }while(toReturn<=0);//to ensure value is not 0

    }

    

    public int intParse(String S){

        int Int=Integer.parseInt(S);        

        return Int;

    }

    

    public void Message(String S){

        JOptionPane.showMessageDialog(null,S);

    }

    

    public void Score(int Qcount){

        Score=Qcount;

    }

    

    public void Score(int Qcount, boolean Correct){

        if(Record != Qcount){

            Record = Qcount;

            if(Correct==false){

                Score--;

            }

        }

    }

    

    public String returnScore(int Qcount){

        String SCORE= Score+"/"+Qcount;

        return SCORE;

    }

    

    public int QuestionList(){

        File Fcount=new File("Question/");

        String[] fileNames = Fcount.list();

        int FCount = 0;

        for (int i = 0; i< fileNames.length; i++)

        {

          if (fileNames[i].contains(".txt"))

            {

              FCount++;

             }

          }

        return FCount;

    }

    

    public int QuestionSelect(int sel){

        //todo new question txt(s)

        QuestionPath="Question/Question"+sel+".txt";

        return sel;

    }

    

    public static void Question(){

        File newFile = new File("Question/Question1.txt");

        if (newFile.exists()){

            System.out.println("Question File aleady Exist");

        }

        else{

            try{

                newFile.createNewFile();

            }catch(Exception e){

                e.printStackTrace();

            }

            try{

                FileWriter fileW = new FileWriter(newFile);

                BufferedWriter buffW = new BufferedWriter(fileW);

                buffW.write("Welcome to Trivia\n" +

                    "Q: How many alphabets are there?\n" +

                    "A: 1. 25\n" +

                    "A: 2. 26\n" +

                    "A: 3. 27\n" +

                    "A: 4. 28\n" +

                    "C: 2\n" +

                    "Q: How many zeros does a million have?\n" +

                    "A: 1. 5\n" +

                    "A: 2. 6\n" +

                    "A: 3. 7\n" +

                    "A: 4. 8\n" +

                    "C: 2\n" +

                    "Q: How many moons are there for planet earth?\n" +

                    "A: 1. 0\n" +

                    "A: 2. 1\n" +

                    "A: 3. 2\n" +

                    "A: 4. 3\n" +

                    "C: 2\n" +

                    "Q: What is the number to call police?\n" +

                    "A: 1. 999\n" +

                    "A: 2. 990\n" +

                    "A: 3. 998\n" +

                    "A: 4. 997\n" +

                    "C: 1\n" +

                    "Q: How many letters is the word alphabet?\n" +

                    "A: 1. 6\n" +

                    "A: 2. 7\n" +

                    "A: 3. 8\n" +

                    "A: 4. 9\n" +

                    "C: 3");

                buffW.close();

                System.out.println("Question File Written");

            }catch(Exception e){

                e.printStackTrace();

            }

        }

    }

    

    public static void Logs(String log){

        File newFile = new File("Results.txt");

        if (newFile.exists()){

            System.out.println("Log File aleady Exist");

            try{

                FileWriter fileW = new FileWriter(newFile, true);

                BufferedWriter buffW = new BufferedWriter(fileW);

                buffW.write(log+"\n");

                buffW.close();

                System.out.println("Log File Written");

            }catch(Exception e){

                e.printStackTrace();

            }

        }

        else{

            try{

                newFile.createNewFile();

            }catch(Exception e){

                e.printStackTrace();

            }

            

            try{

                FileWriter fileW = new FileWriter(newFile);

                BufferedWriter buffW = new BufferedWriter(fileW);

                buffW.write(log);

                buffW.close();

                System.out.println("Log File Written");

            }catch(Exception e){

                e.printStackTrace();

            }

        } 

    }

    

    

    public int getCount(String Patternn)throws Exception{

        FileReader file = new FileReader(QuestionPath);

        BufferedReader reader = new BufferedReader(file);

        

        int count=0;

        

        String textCount="";

        String lineCount = reader.readLine();

        while(lineCount != null){

            textCount += lineCount;

            lineCount = reader.readLine();

        }

        //System.out.println(textCount);

        Pattern p = Pattern.compile(Patternn);

        Matcher m = p.matcher(textCount);

        while (m.find()) {

            if(Patternn.equals(m.group())){

                //System.out.println("Found a " + m.group());

                count++;

            }

        }

        //System.out.println("Question Count "+Qcount); //debug

        //End Question Counter

        return count;

    }

    

    public int getLineCount() throws Exception{

        FileReader file = new FileReader(QuestionPath);

        BufferedReader reader = new BufferedReader(file);

        

        int Lcount=0;

        

        

        String textCount="";

        String lineCount = reader.readLine();

        while(lineCount != null){

            textCount += lineCount;

            lineCount = reader.readLine();

            Lcount++;

        }

        //System.out.println(textCount); //debug

        //System.out.println("Question Count "+Lcount); //debug

        //End Line Counter

        return Lcount;

    }

    

    public String[][] getTXTinput(int Lcount, int Qcount, int Acount) throws Exception {

        String[][] Question = new String[Qcount][(Acount+2)];

        //System.out.println(Qcount+"Qcountdebug");//debug

        //System.out.println((Acount+2)+"Acountdebug");//debug

        FileReader file = new FileReader(QuestionPath);

        BufferedReader reader = new BufferedReader(file);

        String line = reader.readLine();

        line = reader.readLine();

        int j=0;

        int k=2;

        boolean detector = false;

        boolean next = true;

        boolean nextt = true;

        while(line != null){

            for (int i=0; i<(Lcount-1);i++){

                String question = "";

                if(detector==true){

                    detector=false;

                    k=2;

                }

                if(next==true){

                    if(line.toLowerCase().contains("Q:".toLowerCase())){

                        question += line;

                        String substring = question.substring(3);

                        //System.out.println(line);

                        //System.out.println(question);

                        Question[j][0] = substring;

                        detector = true;

                    }//else

                        //System.out.println("Does not contain Q"); //debug

                    next=false;

                    nextt=true;

                }

                if(nextt==true){

                    if(line.toLowerCase().contains("A:".toLowerCase())){

                        question += line;

                        String substring = question.substring(3);

                        //System.out.println(k+"k count");//debug

                        //System.out.println(next+"next");//debug

                        Question[j][k]= substring;

                        k++;

                        next=true;

                    }

                    nextt=false;

                }

                if(line.toLowerCase().contains("C:".toLowerCase())){

                    question += line;

                    String substring = question.substring(3);

                    Question[j][1]= substring;

                    k++;

                    j++;

                    next=true;

                    nextt=true;

                }

                line = reader.readLine();

                nextt=true;

            }

        }

        //System.out.println(Arrays.toString(Question));//debug

        reader.close();

        return Question;

        

    }

    

    public int getLineCountLogg() throws Exception{

        FileReader file = new FileReader("Results.txt");

        BufferedReader reader = new BufferedReader(file);

        

        int Lcount=0;

        

        

        String textCount="";

        String lineCount = reader.readLine();

        while(lineCount != null){

            textCount += lineCount;

            lineCount = reader.readLine();

            Lcount++;

        }

        //System.out.println(textCount); //debug

        //System.out.println("Question Count "+Lcount); //debug

        //End Line Counter

        return Lcount;

    }

    

    public int getLineCountLog(String LogC)throws Exception{

        FileReader file = new FileReader("Results.txt");

        BufferedReader reader = new BufferedReader(file);

        

        int countLog=0;

        

        String textCount="";

        String lineCount = reader.readLine();

        while(lineCount != null){

            textCount += lineCount;

            lineCount = reader.readLine();

        }

        //System.out.println(textCount);

        Pattern p = Pattern.compile(LogC);

        Matcher m = p.matcher(textCount);

        while (m.find()) {

            if(LogC.equals(m.group())){

                //System.out.println("Found a " + m.group());

                countLog++;

            }

        }

        //System.out.println("Question Count "+countLog); //debug

        //End Log Counter

        return countLog;

    }

    

    public String[] getLogs(String LogC,int getLineCountLogg, int QcountLog) throws Exception {

        String[] LogOutput = new String[QcountLog];

        FileReader file = new FileReader("Results.txt");

        BufferedReader reader = new BufferedReader(file);

        String line = reader.readLine();

        int j=0;

        while(line != null){

            for (int i=0; i<getLineCountLogg;i++){

                String LOGOutput = "";

                if(line.toLowerCase().contains(LogC.toLowerCase())){

                    LOGOutput += line;

                    //System.out.println(LOGOutput);//debug

                    LogOutput[j] = LOGOutput;

                    j++;

                }//else//debug

                    //System.out.println("Does not contain log");//debug

                line = reader.readLine();

                

                //System.out.println(Question[i]);

            }

        }

        //System.out.println(Arrays.toString(Question));

        reader.close();

        return LogOutput;

        

    }

    

    //broken code

    /*

    public String[] getLogs(String LogC, int LcountLog)throws Exception{

        String[] getLogs = new String[LcountLog];

        System.out.println(LcountLog+"qwerty");

        FileReader file = new FileReader("Results.txt");

        BufferedReader reader = new BufferedReader(file);

        String line = reader.readLine();

        String LogOutput = "";

        while(line != null){

            LogOutput += line;

            line = reader.readLine();

        }

        

        Pattern p = Pattern.compile(LogC);

        Matcher m = p.matcher(line);

        while (m.find()) {

            if(LogC.equals(m.group())){

                //System.out.println("Found a " + m.group());

                for (int i=0; i<LcountLog;i++){

                int parsevalue = line.length()-19;

                System.out.println(LogOutput+"logoutput");

                String Substring=  LogOutput.substring(0,parsevalue);

                System.out.println(Substring);

                getLogs[i] = Substring;

                line = reader.readLine();

            }

            }

        }

        //System.out.println(Arrays.toString(Question));

        reader.close();

        return getLogs;

    }

    */

    

    //the get below are leagacy

    /*

    public String[] getQuestions(int Lcount, int Qcount) throws Exception {

        String[] Question = new String[Qcount];

        FileReader file = new FileReader(QuestionPath);

        BufferedReader reader = new BufferedReader(file);

        String line = reader.readLine();

        int j=0;

        while(line != null){

            for (int i=0; i<Lcount;i++){

                String question = "";

                if(line.toLowerCase().contains("Q:".toLowerCase())){

                    question += line;

                    System.out.println(question);

                    Question[j] = question;

                    j++;

                }else

                    System.out.println("Does not contain Q");

                line = reader.readLine();

                

                //System.out.println(Question[i]);

            }

        }

        //System.out.println(Arrays.toString(Question));

        reader.close();

        return Question;

        

    }

    

    public String[] getAnswer(int Lcount, int Acount) throws Exception {

        String[] Answer = new String[Acount];

        FileReader file = new FileReader(QuestionPath);

        BufferedReader reader = new BufferedReader(file);

        String line = reader.readLine();

        int j=0;

        while(line != null){

            for (int i=0; i<Lcount;i++){

                String question = "";

                if(line.toLowerCase().contains("Q:".toLowerCase())){

                    question += line;

                    System.out.println(question);

                    Answer[j] = question;

                    j++;

                }else

                    System.out.println("Does not contain Q");

                line = reader.readLine();

                

                //System.out.println(Question[i]);

            }

        }

        System.out.println(Arrays.toString(Answer));

        reader.close();

        return Answer;

        

    }

    */

}