Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a Java application that: Implements Object serialization. Implements read

ID: 674950 • Letter: C

Question

Create a Java application that: Implements Object serialization. Implements reading, writing and searching a random access file. Implements API and user defined exceptions. Catches and recovers from thrown exceptions Develops a program with several classes. Creates UML class diagrams. Prep Reading Absolute Java Chapters 1 - 10 Project Requirements: In this project you will implement a trivia game. It will ask random trivia questions, evaluate their answers and keep score. The project will also have an administrative module that will allow for managing the question bank. Question bank management will include adding new questions, deleting questions and displaying all of the questions, answers and point values. Project detailsCreate a class to administer the question bank with the following functionality: Command line menu. Stores question data in a Random Access File (See details of file structure below) Enter new questions including answer and question point value. Point value should be 1 to 5. Delete questions by searching for a question in the random access file. I would suggest assigning a question id number to each question. (hint: Static variable) Display all of the questions, associated answers and point value. The question bank must be stored in a binary Random Access File with the following record structure Question (@50 bytes) – ASCII char use one byte Answer (@20 bytes) Question point value (an int) Create and use user defined exception to ensure question and answer do not exceed maximum number of bytes and the point value is between 1 and 5(inclusive) For the purposes of this project the question bank will contain at least 15 questions. Example of text menu: Trivia Game Administration 1. List all questions 2. Delete question 3. Add question 4. Quit Enter choice: Create a class for the players information with the following functionality Player’s real name Player’s gamer nick name Current total score. Total score is a summation of all the Player’s game sessions. Ability to store the user object to a serialized file, the file name is the user real name such as johnsmith.dat. No need to handle duplicate file names. Create a class for questions including question, answer, value and a question ID Accessor methods to return all instance fields. Create a class for the trivia game with the following functionality. Stores a collection of Question objects. Using random number generation to read 5 questions from the question bank and stores them in the collection. Remember the questions are stored in a record format. Returns the next question object in the collection. Evaluate the answer and returns the outcome. The evaluation should ignore case. Create a class to run the game Command line Ask if new or existing user. If new user create a new user object and ask for required user information(name, nick name) If existing user prompt for user name read user information from serialized file into a user object. If file not found handle exception robustly by providing error message and asking again. Create trivia game object Start the game, the game sequence is Display a question Prompt for an answer Evaluate the answer Display the evaluation results Update the users total score Display the user current game score. Continue to display new questions until current game is over. (5 questions) Once game is over, allow user to play again or quit If user quit Display his nick name, current game score and total score. Write or overwrite the current user data to the serialized file. Allow another user to play or quit the program.

Explanation / Answer

package triviagame;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.ObjectInputStream;

import java.io.ObjectOutputStream;

import java.io.Serializable;

public class Player implements Serializable {

    String PlayerName;

    String NickName;

    static int totalScore;

    public Player()

    {

        PlayerName="";

        NickName="";

        totalScore+=0;

    }

    public Player(String name, String nick, int score) {

        PlayerName=name;

        NickName=nick;

        totalScore+=score;

        }

    public void setTotalScore(int s)

    {

        totalScore+=s;

    }

    public int getTotalScore()

    {

        return totalScore;

    }

public Question[] readQuestions() throws IOException {

        int min=1, max=15;

        try{

    RandomAccessFile raf = new RandomAccessFile("QBank", "rw");

    Random rand = new Random();

   

    // nextInt excludes the top value so we have to add 1 to include the top value

    for(int i=0;i<5;i++)

    {

    int randomNum = rand.nextInt((max - min) + 1) + min;

    raf.seek(0);

    int id = raf.readInt();

    if(id!=randomNum)

    {

      raf.seek(50+20+4);

    }

    else

      Q[i].setQuestion(raf.readUTF());

      Q[i].setAnswer(raf.readUTF());

      Q[i].setValue(raf.readInt());

    }

    raf.close();

        }

        catch(Exception e)

        {

          System.out.println(e.toString());

        }

return Q;

    }

//Total score is a summation of all the Player’s game sessions.

//Ability to store the user object to a serialized file, the file name is the

    //user real name such as johnsmith.dat. No need to handle duplicate file names.

    public void writePlayer(String name, String nick, int score)

    {

        Player player=new Player(name,nick,score);

        try{

            FileOutputStream fout = new FileOutputStream("johnsmith.dat");

            ObjectOutputStream oos = new ObjectOutputStream(fout);  

            oos.writeObject(player);

                   oos.close();

                  }catch(Exception ex){

               System.out.println(ex.toString());

                  }

    }

    public Player readPlayer(String name)

    {

        Player player=new Player();

        try{

            FileInputStream fin = new FileInputStream("johnsmith.dat");

            ObjectInputStream oos = new ObjectInputStream(fin);  

            player=(Player) oos.readObject();

                   oos.close();

                  }catch(Exception ex){

               System.out.println(ex.toString());

                  }

        return player;

    }

}

//=========================================================================

package triviagame;

/*Create a class for questions including

question, answer, value and a question ID

Accessor methods to return all instance fields.*/

public class Question {

    char question[];

    char answer[];

    int value;

    static int QID;

    public Question()

    {

    question=new char[50];

    answer=new char[20];

    value=0;

    }

     public Question(String Q,String A, int val,int ID)throws QuestionException

    {

    question=new char[50];

    if(Q.length()>50)

    throw new QuestionException("Question length is not in range");

    else

    question=Q.toCharArray();

    answer=new char[20];

    if(A.length()>20)

     throw new QuestionException("Answer length is not in range");

    else  

    answer=A.toCharArray();

    if(val>=1 && val<=5)

        value=val;

    else throw new QuestionException("Question Value is not in range");

    QID=ID;

    }

    public String getQuestion()

    {

        return question.toString();

    }

    public String getAnswer()

    {

        return answer.toString();

    }

    public int getValue()

    {

        return value;

    }

    public int getQID()

    {

        return QID;

    }

  

    public void setQuestion(String Q)throws QuestionException

    {

    question=new char[50];

    if(Q.length()>50)

    throw new QuestionException("Question length is not in range");

    else

    question=Q.toCharArray();

    }

    public void setAnswer(String A)throws QuestionException

    {

    answer=new char[50];

    if(A.length()>20)

     throw new QuestionException("Answer length is not in range");

    else  

    answer=A.toCharArray();

    }

    public void setValue(int val)throws QuestionException

    {

    if(val>=1 && val<=5)

        value=val;

    else

        throw new QuestionException("Question Value is not in range");

    }

    public void setQid(int ID)

    {

    QID=ID;

    }

}

//===========================================================================

package triviagame;

public class QuestionBank {

    Question Q[];

    static int id;

    public QuestionBank()

    {

        Q=new Question[15];

    }

    public void addQuestion(Question q)

    {

        Q[id++]=q;

    }

    public void deleteQuestion(int index) throws QuestionException

    {

        Q[index].setAnswer(null);

        Q[index].setQuestion(null);

        Q[index].setValue(0);

        Q[index].setQid(-1);

    }

}

//================================================================================

package triviagame;

public class QuestionException extends Exception

{

    public QuestionException(String msg)

    {

        super(msg);

    }

}  

   

//==============================================================================

package triviagame;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.util.Random;

public class TriviaGame {

    Question Q[];

    int score;

    public TriviaGame()

    {

        Q=new Question[5];

        score=0;

    }

    public int evaluate(String userAnswer, int Qid)

    {

        if(userAnswer.equalsIgnoreCase(Q[Qid].getAnswer()))

        {

            score=Q[Qid].getValue();

        }

        else

            score=0;

        return score;

    }

    public Question[] readQuestions() throws IOException {

        int min=1, max=15;

        try{

    RandomAccessFile raf = new RandomAccessFile("QBank", "rw");

    Random rand = new Random();

   

    // nextInt excludes the top value so we have to add 1 to include the top value

    for(int i=0;i<5;i++)

    {

    int randomNum = rand.nextInt((max - min) + 1) + min;

    raf.seek(0);

    int id = raf.readInt();

    if(id!=randomNum)

    {

      raf.seek(50+20+4);

    }

    else

      Q[i].setQuestion(raf.readUTF());

      Q[i].setAnswer(raf.readUTF());

      Q[i].setValue(raf.readInt());

    }

    raf.close();

        }

        catch(Exception e)

        {

          System.out.println(e.toString());

        }

return Q;

    }

public static void incrementReadCounter(RandomAccessFile raf)

      throws IOException {

    long currentPosition = raf.getFilePointer();

    raf.seek(currentPosition);

}

}

//=====================================================================

package triviagame;

import java.util.Scanner;

public class TriviaGameDemo {

    public static void main(String[] args) {

        Player User=new Player();

        int k=0;

    int choice;

    System.out.println(" Trivia Game Administration");

    System.out.println(" 1. List all questions");

    System.out.println(" 2. Delete question");

    System.out.println(" 3. Add question");

    System.out.println(" 4. Quit");

    System.out.println(" ------------------------------");

    System.out.println(" Enter choice:");

    Scanner scan=new Scanner(System.in);

    choice=scan.nextInt();

    System.out.println(" New User or Existing User?<n/e>");

    String user=scan.next();

    String name="";

    String nick="";

    if(user=="n")

    {

      System.out.println(" Enter name and Nick Name");

        name=scan.next();

        nick=scan.next();

       User= new Player(name, nick, 0);

    }

    else

    {

        System.out.println(" Enter UserName");

        String uname=scan.next();

        User.readPlayer(uname);

    }

    String ch="p";

    while(ch.equalsIgnoreCase("p"))

    {

     

      TriviaGame TG=new TriviaGame();

      try{

      Question Q[]=TG.readQuestions();

      }

      catch(Exception e)

      {

         

      }

      int i;

      for(i=0;i<5;i++)

      {

      System.out.println("Question:"+TG.Q[k]);

      System.out.println("Enter your answer:");

      String ans=scan.next();

      int s=TG.evaluate(ans, k);

      System.out.println("Your current Score:"+s);

      User.setTotalScore(s);

      }

      if(i==5)

      System.out.println("Game Over");   

      System.out.println("Do u want to Play again or Quit? <p,q>");

      ch=scan.next();

      if(ch.equalsIgnoreCase("q"))

      {

      System.out.println("Name:"+name);

      System.out.println("Nick Name"+nick);

      System.out.println("Total Score"+User.getTotalScore() );

      }

    }

    User.writePlayer(ch, ch, choice);

    }

}