Question

In: Computer Science

Create a Java class named Trivia that contains three instance variables, question of type String that...

Create a Java class named Trivia that contains three instance variables, question of type String that stores the question of the trivia, answer of type String that stores the answer to the question, and points of type integer that stores the points’ value between 1 and 3 based on the difficulty of the question.

Also create the following methods:

  1. getQuestion( ) – it will return the question.
  2. getAnswer( ) – it will return the answer.
  3. getPoints( ) – it will return the point
  4. setQuestion( String ) – sets the value of the question variable
  5. setAnswer( String ) – sets the value of the answer variable
  6. setPoints( int ) – sets the value of the points variable
  7. Constructor to initialize the instance variables.
  8. Overload Constructor to set the instance variables.
  9. Add any other methods you need such as equal( ), toString( ), display( ), calcPoints( )...

Create Java application that contains a main method that plays a simple Trivia game. The game should have 5 questions. Each question has a corresponding answer and point value between 1 and 3. Implement the game using an array of 5 Trivia objects.

Next, open a binary file and store those 5 Trivia objects into a binary file then close the file. Open the file again to read each question one at a time and store them into an array of objects.

Randomly, display a question and allow the player to enter an answer.

If the player’s answer matches the actual answer, the player wins the number of points for that question. If the player’s answer is incorrect, the player wins no points for the question. Make sure the answer is not case sensitive and it is only one word or two words at most. The program should show the correct answer if the player is incorrect. After the player has answered all five questions, the game is over and your program should display the player’s total score.

Solutions

Expert Solution

Coding :

Trivia.java

import java.io.Serializable;
import java.util.Scanner;

public class Trivia implements Serializable {
    private String question;
    private String answer;
    private int Points;

    public Trivia(){
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the Question : ");
        String q = sc.nextLine();
        setQuestion(q);
        System.out.println("Enter the Answer : ");
        String ans = sc.nextLine();
        setAnswer(ans);
        System.out.println("Enter the Points (1 to 3) : ");
        int p = sc.nextInt();
        setPoints(p);
    }

    public Trivia(String q, String a, int p){
        setQuestion(q);
        setAnswer(a);
        setPoints(p);
    }

    public String getQuestion() {
        return question.trim();
    }

    public String getAnswer() {
        return answer.toLowerCase();
    }

    public int getPoints() {
        return Points;
    }

    public void setQuestion(String question) {
        this.question = question.trim();
    }

    public void setAnswer(String answer) {
        this.answer = answer.trim();
    }

    public void setPoints(int points) {
        Points = points;
    }

    private boolean equal(String ans){
        if(ans==getAnswer())
            return true;
        else return false;
    }

    public void display(String ans){
        if (equal(ans)==true)
            System.out.println("\nThe answer is correct");
        else {
            System.out.println("\nThe answer is incorrect");
            System.out.println("\nCorrect Answer : " + answer);
        }
    }

    public int calcPoints(int t,String ans){
        if(equal(ans)==true)
         return t + Points;
        else return t;
    }
}

Main.java

import java.io.*;
import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        Trivia T [] = new Trivia[5];

        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the Question : ");
        String q = sc.nextLine();
        System.out.println("\nEnter the Answer : ");
        String ans = sc.nextLine();
        System.out.println("\nEnter the Points (1 to 3) : ");
        int p = sc.nextInt();
        Trivia t = new Trivia(q,ans,p);
        T[0] = t;

        int j = 1;
        while (j<5) {
            T[j] = new Trivia();
            j++;
        }

        File f = new File("sample.dat");
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(f));
        out.writeObject(T);
        out.close();

        ObjectInputStream in = new ObjectInputStream(new FileInputStream(f));
        Trivia Q [] = (Trivia[]) in.readObject();
        List<Trivia> triviaList = Arrays.asList(Q);
        Collections.shuffle(triviaList);
        triviaList.toArray(Q);

        int total = 0;
        for (int i = 1; i <= 5; i++) {
            System.out.println("\nQuestion " + i + " : " + Q[i-1].getQuestion());
            System.out.println("\nType Your Answer : ");
            String answer = sc.next();
            Q[i].display(ans);
            total = Q[i].calcPoints(total,ans);

        }

        System.out.println("Your Points are : " + total);
        in.close();
    }
}

Explanation :

Trivia.java :

  • It consists of two constructors: a default one and a parameterized constructor.
  • The parameterized constructor takes a question, its answer, and points to be allocated on the correct answer as parameters.
  • Three getters and setters for instance variable question, answer, and Points which are used for getting and setting questions, answer, and points are here respectively.
  • the equal() method is for comparing entered answers with answers for the question. If the answer is correct it returns true otherwise returb=ns false.
  • display() method is used for displaying a message for the entered answer. If the entered answer is correct then it shows the "Correct Answer" message otherwise shows the "Incorrect Answer" message and displays the correct one.
  • calcPoints() method for calculating total points. It returns newly calculated total points.

Main.java:

  • T is an array for storing Trivia class Objects.
  • Then for First Question, we have necessary input like a question, answer, and points and then passed to the parameterized constructor.
  • while loop is made for taking the next 4 questions by default/non-parameterized constructor.
  • We have created a file object of the "sample.dat" file. If the file is present in the directory, its file object is created otherwise the new file is created and then its file object.
  • Then we have created objects of ObjectOutputStream to store objects of Trivia class in the file.
  • The following line writes the whole Trivia array into a stream of objects into a binary file.
out.writeObject(T);
  • Then we have closed the file.
  • Then we have created Object of ObjectInputStream to read a stream of data from the binary file.
  • The following line reads the whole Trivia array from a stream of objects in the binary file and stores it as a new area object of Trivia class Q.
in.writeObject(T);
  • We have then converted it into a list of Trivia Objects and shuffled it and then stored it back in Q array of Trivia Objects.
  • for loop is created for printing questions and taking entered answers and checking answers and displaying the appropriate messages.
  • A variable total is created for storing total points of the user.
  • Then we display total points.

Output :

"D:\Softwares\IntelliJ IDEA\IntelliJ IDEA Community Edition 2020.2.1\jbr\bin\java.exe" "-javaagent:D:\Softwares\IntelliJ IDEA\IntelliJ IDEA Community Edition 2020.2.1\lib\idea_rt.jar=63298:D:\Softwares\IntelliJ IDEA\IntelliJ IDEA Community Edition 2020.2.1\bin" -Dfile.encoding=UTF-8 -classpath C:\Users\niran\IdeaProjects\Animal\out\production\Animal Main
Enter the Question : 
Capital of India

Enter the Answer : 
delhi

Enter the Points (1 to 3) : 
1
Enter the Question : 
capital of Pakistan
Enter the Answer : 
karachi
Enter the Points (1 to 3) : 
2
Enter the Question : 
'1' is a
Enter the Answer : 
int
Enter the Points (1 to 3) : 
2
Enter the Question : 
'a' is a
Enter the Answer : 
char
Enter the Points (1 to 3) : 
3
Enter the Question : 
'2.0'is a
Enter the Answer : 
float
Enter the Points (1 to 3) : 
1

Question 1 : Capital of India

Type Your Answer : 
delhi

The answer is correct

Question 1 : capital of Pakistan

Type Your Answer : 
karachi

The answer is correct


Question 2 : 'a' is a

Type Your Answer : 
int

The answer is incorrect

Correct Answer : char

Question 3 : '2.0'is a

Type Your Answer : 
float

The answer is correct

Question 4 : '1' is a

Type Your Answer : 
int

The answer is correct

Your Points are : 6

Process finished with exit code 0

Related Solutions

Create a Java class named Trivia that contains three instance variables, question of type String that...
Create a Java class named Trivia that contains three instance variables, question of type String that stores the question of the trivia, answer of type String that stores the answer to the question, and points of type integer that stores the points’ value between 1 and 3 based on the difficulty of the question. Also create the following methods: getQuestion( ) – it will return the question. getAnswer( ) – it will return the answer. getPoints( ) – it will...
Define a class named Document that contains an instance variable of type String named text that...
Define a class named Document that contains an instance variable of type String named text that stores any textual content for the document. Create a method named toString that returns the text field and also include a method to set this value. Next, define a class for Email that is derived from Document and includes instance variables for the sender, recipient, and title of an email message. Implement appropriate set and get methods. The body of the email message should...
Create a Java class named Package that contains the following: Package should have three private instance...
Create a Java class named Package that contains the following: Package should have three private instance variables of type double named length, width, and height. Package should have one private instance variable of the type Scanner named input, initialized to System.in. No-args (explicit default) public constructor, which initializes all three double instance variables to 1.0.   Initial (parameterized) public constructor, which defines three parameters of type double, named length, width, and height, which are used to initialize the instance variables of...
Design a class named Student that contains the followingprivate instance variables: A string data field name...
Design a class named Student that contains the followingprivate instance variables: A string data field name for the student name. An integer data field id for the student id. A double data field GPA for the student GPA. An integer data field registeredCredits. It contains the following methods: An empty default constructor. A constructor that creates a student record with a specified id and name. The get and set methods for id, name, GPA, and registeredCredits. A method called registerCredit...
with PHP Create a class called Employee that includes three instance variables—a first name (type String),...
with PHP Create a class called Employee that includes three instance variables—a first name (type String), a last name (type String) and a monthly salary int). Provide a constructor that initializes the three instance data member. Provide a set and a get method for each instance variable. If the monthly salary is not positive, do not set its 0. Write a test app named EmployeeTest that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary....
(Java Problem) Create a Produce class that have an instance variable of type String for the...
(Java Problem) Create a Produce class that have an instance variable of type String for the name, appropriate constructors, appropriate accessor and mutator methods, and a public toString() method. Then create a Fruit and a Vegetable class that are derived from Produce. These classes should have constructors that take the name as a String, the price (this is the price per box) as a double, the quantity as an integer, and invoke the appropriate constructor from the base class to...
java: create a conplete class named patient. the patient class shouls include teo private instance variables...
java: create a conplete class named patient. the patient class shouls include teo private instance variables named PatientID of type int lastName of type string. include all the parts of a well-formed class described. set the instance variable defaults to appropriate values.
CS 209 Data Structure 3. a. Create a class named Point3D that contains 3 instance variables...
CS 209 Data Structure 3. a. Create a class named Point3D that contains 3 instance variables x, y, and z. b. Create a constructor that sets the variables. Also, create get and set methods for each variable. c. Create a toString() method. d. Make Point3D implement Comparable. Also, create a compareTo(Point3D other) method that compares based on the x-coordinate, then y-coordinate for tiebreakers, then z-coordinate for tiebreakers. For example, (1, 2, 5) comes before (2, 1, 4), which comes before...
Define a class named Document that contains an instance variable of type String named text that stores any textual content for the document.
IN JavaDefine a class named Document that contains an instance variable of type String named text that stores any textual content for the document. Create a method named toString that returns the text field and also include a method to set this value. Next, define a class for Email that is derived from Document and includes instance variables for the sender, recipient, and title of an email message. Implement appropriate set and get methods. The body of the email message...
Define a class named Document that contains an instance variable of type String named text that stores any textual content for the document.
Code in Java Define a class named Document that contains an instance variable of type String named text that stores any textual content for the document. Create a method named toString that returns the text field and also include a method to set this value.Next, define a class for Email that is derived from Document and includes instance variables for the sender, recipient, and title of an email message. Implement appropriate set and get methods. The body of the email message...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT