GUI-based application for a Trivia game

  • (2 Pages)
  • +
  • 1
  • 2

19 Replies - 10708 Views - Last Post: 03 December 2010 - 01:06 PM Rate Topic: -----

#1 Gijimu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-December 10

GUI-based application for a Trivia game

Posted 01 December 2010 - 10:52 AM

I have to write a GUI-based application that allows a user to play a simple trivia game. The game should have 5 questions. Each question should have a corresponding answer and a point value between 1 and 3, based on the difficulty of the question. Manually hardcode the 5 questions, answers and point values into your program.

When creating the GUI for the game interface, use a layout of your choice with the appropriate text fields, labels and buttons to implement your design. The program should ask the player each question one at a time 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 that question and the program should show the correct answer. After the player has answered all 5 questions, the game is over and the program should display the player’s total score and then terminate. This is what I have so far any help
would be appreciated.


import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class TriviaGame {

    public static void main(String[] args, Question[] qArray) throws IOException {

        // Constants
        final int NUM_QUESTIONS = 5;
        final int NUM_PLAYERS = 1;

        // Variables
        int playerTurn = 1; // The current player
        int questionNum; // The current question number
        int playerAnswer; // The player's chosen answer
        int player1points = 0; // Player's points


        // Create an array of Player objects for player #1 and player #2.
        Player[] players = new Player[NUM_PLAYERS];
        for (int i = 0; i < NUM_PLAYERS; i++) {
            players[i] = new Player(i + 1);

        }



        // Create an array to hold Question objects.
        Question[] questions = new Question[NUM_QUESTIONS];



        // Initialize the array with data.
        initQuestions(questions);

        // Play the game.
        for (int i = 0; i < NUM_QUESTIONS; i++) {

            // Display the question.
            TriviaGame.displayQuestion(qArray[i], playerTurn);

            // Get the player's answer.
            players[playerTurn - 1].chooseAnswer();

            // See if the correct answer was chosen.
            if (qArray[i].getCorrectAnswerNumber()
                    == players[playerTurn - 1].getCurrentAnswer()) {

                players[playerTurn - 1].incrementPoints();

            }
            // See if the the player chose the wrong answer.
            // do nothing


        }
        // Show the game results.
        showGameResults(players);
        /**
         * The initQuestions method uses the contents of the trivia.txt file to
         * populate the qArray parameter with Question objects.
         */


    public static initQuestions(Question qArray[]) throws IOException {

        // Open the trivia.txt file.
        File file = new File("trivia.txt");
        Scanner inputFile = new Scanner(file);

        // Populate the qArray with data from the file.
        for (int i = 0; i < qArray.length; i++) {
            // Create a Question object in the array.
            qArray[i] = new Question();

            // Get the question text from the file.
            qArray[i].setQuestion(inputFile.nextLine());

            // Get the possible answers.
            for (int j = 1; j <= 4; j++) {
                qArray[i].setPossibleAnswer(inputFile.nextLine(), j);

            }
            // Get the correct answer.
            qArray[i].setCorrectAnswerNumber(Integer.parseInt(inputFile.nextLine()));

        }


    }

    public static void displayQuestion(Question q, int playerNum) {
        // Display the player number
        System.out.println("Question for player #" + playerNum);
        System.out.println("------------------------");

        // Display the question.
        System.out.println(q.getQuestionText());
        for (int i = 1; i <= 4; i++) {
            System.out.println(i + ". " + q.getPossibleAnswer(i));

        }
    }

    public static void showGameResults(Player[] players) {
        // Display the stats.
        System.out.println("Game Over!");
        System.out.println("Player's points: " + players[0].getPoints());

        // Declare the winner.
        if (players[0].getPoints() > players[1].getPoints()) {
            System.out.println("Player wins!");
        }

    }

    public final class Question {
        // Constant for the number of answers

        public final int NUM_ANSWERS = 5;
        // The trivia question
        private String questionText;
        // An array to hold possible answers.
        private String possibleAnswers[] = new String[NUM_ANSWERS];
        // The number (1, 2, 3, or 4) of the correct answer.
        private int correctAnswer;

        //Constructor
        public Question() {
            // Initialize all fields to "" or 0;
            questionText = "";
            correctAnswer = 0;
            for (int i = 1; i < NUM_ANSWERS; i++) {
                setPossibleAnswer("", i);
            }


        }

        public void setQuestion(String question) {
            this.questionText = question;           //Sets the question

        }

        public void setPossibleAnswer(String text, int num) {
            this.possibleAnswers[num] = text;       //Sets possible Answer

        }

        public void setCorrectAnswerNumber(int num) {
            this.correctAnswer = num;               //Sets correct Answer

        }

        public String getQuestionText() {
            return this.questionText;               //Returns Question Text
        }

        public String getPossibleAnswer(int num) {
            return this.possibleAnswers[num];       //Returns Possible Answer
        }

        public int getCorrectAnswerNumber() {
            return this.correctAnswer;              //Returns Correct Answer
        }

        public String getCorrectAnswer() {
            return this.possibleAnswers[this.correctAnswer];    //Returns Possible Answer
        }
    }

    public class Player {

        private int playerNumber;  // The player number
        private int points;        // Player's points
        private int currentAnswer; // Current chosen answer

        //Constructor
        public Player(int playerNum) {
            playerNumber = playerNum;
            points = 0;

        }

        public void chooseAnswer() {
            // Create a Scanner object for keyboard input.
            // Get the user's chosen answer.
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Please enter your Answer");    //Asks user for a number
            this.currentAnswer = keyboard.nextInt();

        }

        public int getCurrentAnswer() {
            return this.currentAnswer;          //Returns Current Answer

        }

        public void incrementPoints() {
            this.points++;                      //Increments the points

        }

        public int getPoints() {
            return this.points;                 //Returns the points

        }
    }


public class Test {
	{
		MyPanel gui = new MyPanel();
		gui.setVisible(true);
	}
}
class MyPanel extends JFrame implements ActionListener {
	private JPanel redPanel;
	private JPanel whitePanel;
	private JPanel bluePanel;

	public MyPanel() {
		super("Panel Demonstration");
		setSize(300, 200);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLayout(new BorderLayout());

		JPanel biggerPanel = new JPanel();
		biggerPanel.setLayout(new GridLayout(1, 3));
		add(biggerPanel, BorderLayout.CENTER);

		redPanel = new JPanel();
		whitePanel = new JPanel();
		bluePanel = new JPanel();

		redPanel.setBackground(Color.LIGHT_GRAY);
		whitePanel.setBackground(Color.LIGHT_GRAY);
		bluePanel.setBackground(Color.LIGHT_GRAY);

		biggerPanel.add(redPanel);
		biggerPanel.add(whitePanel);
		biggerPanel.add(bluePanel);

		JPanel buttonPanel = new JPanel();
		buttonPanel.setBackground(Color.LIGHT_GRAY);
		buttonPanel.setLayout(new FlowLayout());
		add(buttonPanel, BorderLayout.SOUTH);
		JButton redButton = new JButton("Red");
		JButton whiteButton = new JButton("White");
		JButton blueButton = new JButton("Blue");

		redButton.setBackground(Color.RED);
		whiteButton.setBackground(Color.WHITE);
		blueButton.setBackground(Color.BLUE);

		redButton.addActionListener((ActionListener) this);
		whiteButton.addActionListener((ActionListener) this);
		blueButton.addActionListener((ActionListener) this);

		buttonPanel.add(redButton);
		buttonPanel.add(whiteButton);
		buttonPanel.add(blueButton);
	}

	public void actionPerformed(ActionEvent e) {
		String buttonString = e.getActionCommand(); //recovers the string from the
										//button that was pressed

		if (buttonString.equals("Red"))
			redPanel.setBackground(Color.RED);
		else if (buttonString.equals("White"))
			whitePanel.setBackground(Color.WHITE);
		else if (buttonString.equals("Blue"))
			bluePanel.setBackground(Color.BLUE);
		else
			System.out.println("Unexpected error.");
	}



        private void add(JPanel buttonPanel, String SOUTH) {
            throw new UnsupportedOperationException("Not yet implemented");
        }

        private void setLayout(BorderLayout borderLayout) {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    }
}


This post has been edited by macosxnerd101: 01 December 2010 - 10:54 AM
Reason for edit:: Please use code tags


Is This A Good Question/Topic? 0
  • +

Replies To: GUI-based application for a Trivia game

#2 masijade  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 196
  • View blog
  • Posts: 580
  • Joined: 03-April 10

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 11:34 AM

And your question is?
Was This Post Helpful? 0
  • +
  • -

#3 Gijimu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-December 10

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 12:40 PM

View Postmasijade, on 01 December 2010 - 10:34 AM, said:

And your question is?



I cannot get the application to run I have 3 errors regarding non-static variables cannot be referenced from a static content the errors are at lines 32, 75 and 84. Trying to figure out how to correct the errors to make the program to work hopefully.
Was This Post Helpful? 0
  • +
  • -

#4 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 01:49 PM

Firstly, you CANNOT put methods inside other methods. You do that through the ENTIRE program. You need to make sure you have the proper numbers of { and }. You need to move your class variable out of main() and put them into the class so that all your other methods can see them. Right now, you are having serious issues with scope. Also, static is generally not a great thing with some notable exceptions. You should get rid of the statics except main() and use objects instead of methods.

Please read my tutorial on scope and static methods. It will really help you:
http://www.dreaminco...atic-variables/
Was This Post Helpful? 0
  • +
  • -

#5 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,913
  • Joined: 06-March 08

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 07:20 PM

Don't you think that having said that your code didn't even compile would have help

The compiler will tell you at which lines you have the non static variables accessed in a static context. That would help
Was This Post Helpful? 0
  • +
  • -

#6 Gijimu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-December 10

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 08:05 PM

how do you change the non-static to static then?
Was This Post Helpful? 0
  • +
  • -

#7 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2876
  • View blog
  • Posts: 11,051
  • Joined: 15-July 08

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 08:16 PM

You add the static keyword. But really, you should consider what I said earlier about static variables and methods. Be wary about bad class design.
Was This Post Helpful? 0
  • +
  • -

#8 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,913
  • Joined: 06-March 08

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 08:19 PM

View PostGijimu, on 01 December 2010 - 09:05 PM, said:

how do you change the non-static to static then?

Java is an Object Oriented language and desserve to be treated so.

You need a public static void main(String[] args) method to start the application.
The role of this method is to create an instance object, in your case, a TriviaGame object
then everything should happen in this TriviaGame object.
So your main should be:

This syntax is wrong
public static void main(String[] args, Question[] qArray)
the main() method has only one argument which is an array of arguments

public static void main(String[] args) {
    new TriviaGame();
}


This should be the onlyest static method in all your class.

Remove the static in front of all methods that are static.
Put the code that is actualyy in your main() into the constructor of TriviaGame

Happy coding
Was This Post Helpful? 1
  • +
  • -

#9 Gijimu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-December 10

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 08:39 PM

Where would I implement the 5 questions and 5 answers in the application, so that it would appear on the JFrame.




import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;


public class TriviaGame {

    public static void main(String[] args) {
        TriviaGame triviaGame = new TriviaGame();


        MyWindow w = new MyWindow(Color.BLUE);
        w.setVisible(true);
        MyWindow c = new MyWindow(Color.RED);
        w.setVisible(true);
    }

    static void displayQuestion(EndingListener.Question question, int playerTurn) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

class MyWindow extends JFrame {

    public MyWindow(Color theColor) {
        super();
        setSize(300, 200);
        setTitle("Trivia Quest");
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        getContentPane().setBackground(theColor);

        JButton endButton = new JButton("Click to end program.");
        endButton.addActionListener((ActionListener) new EndingListener());
        add(endButton);
    }
}
//class EndingListener could have been a private inner class of MyWindow
class EndingListener implements ActionListener {

    private class NUM_PLAYER {

        public NUM_PLAYER() {
        }
    }

    private class i<T> {

        public i() {
        }
    }

    private class qArray {

        public qArray() {
        }
    }

    public void actionPerformed(ActionEvent e) {
        System.exit(0);



        // Constants
        final int NUM_QUESTIONS = 5;
        final int NUM_PLAYERS = 1;

        // Variables
        int playerTurn = 1; // The current player
        int questionNum; // The current question number
        int playerAnswer; // The player's chosen answer
        int player1points = 0; // Player's points


        // Create an array of Player objects for player.
        Player[] p = new Player[NUM_PLAYERS];
        Player[] player = null;
        for (int i = 0; i < NUM_PLAYERS; i++) {
        }




        // Create an array to hold Question objects.
        Question[] questions = new Question[NUM_QUESTIONS];



        // Initialize the array with data.
        Question[] qArray = null;

        // Play the game.
        for (int i = 0; i < NUM_QUESTIONS; i++) {

            // Display the question.
            TriviaGame.displayQuestion(qArray[i], playerTurn);

            // Get the player's answer.
            player[playerTurn - 1].chooseAnswer();

            // See if the correct answer was chosen.
            if (qArray[i].getCorrectAnswerNumber()
                    == player[playerTurn - 1].getCurrentAnswer()) {

                player[playerTurn - 1].incrementPoints();

            }
            // See if the the player chose the wrong answer.
            // do nothing


        }
        // Show the game results.
        showGameResults(player);
        /**
         * The initQuestions method uses the contents of the trivia.text file to
         * populate the qArray parameter with Question objects.
         */
        class initQuestions {
        }
        // Open the trivia.txt file.
        File file = new File("trivia.txt");
        Scanner inputFile = null;

        try {
            inputFile = new Scanner(file);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(EndingListener.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Populate the qArray with data from the file.
        for (int i = 0; i < qArray.length; i++) {



            // Get the question text from the file.
            qArray[i].setQuestion(inputFile.nextLine());

            // Get the possible answers.
            for (int j = 1; j <= 4; j++) {
                qArray[i].setPossibleAnswer(inputFile.nextLine(), j);

            }
            // Get the correct answer.
            qArray[i].setCorrectAnswerNumber(Integer.parseInt(inputFile.nextLine()));

        }


    }

    public void displayQuestion(Question q, int playerNum) {
        // Display the player number
        System.out.println("Question for player #" + playerNum);
        System.out.println("------------------------");

        // Display the question.
        System.out.println(q.getQuestionText());
        for (int i = 1; i <= 4; i++) {
            System.out.println(i + ". " + q.getPossibleAnswer(i));

        }
    }

    public void showGameResults(Player[] players) {
        // Display the stats.
        System.out.println("Game Over!");
        System.out.println("Player's points: " + players[0].getPoints());

        // Declare the winner.
        if (players[0].getPoints() > players[1].getPoints()) {
            System.out.println("Player wins!");
        }

    }

    public final class Question {
        // Constant for the number of answers

        public final int NUM_ANSWERS = 5;
        // The trivia question
        private String questionText;
        // An array to hold possible answers.
        private String possibleAnswers[] = new String[NUM_ANSWERS];
        // The number (1, 2, 3, or 4) of the correct answer.
        private int correctAnswer;

        //Constructor
        public Question() {
            // Initialize all fields to "" or 0;
            questionText = "";
            correctAnswer = 0;
            for (int i = 1; i < NUM_ANSWERS; i++) {
                setPossibleAnswer("", i);
            }


        }

        public void setQuestion(String question) {
            this.questionText = question;           //Sets the question

        }

        public void setPossibleAnswer(String text, int num) {
            this.possibleAnswers[num] = text;       //Sets possible Answer

        }

        public void setCorrectAnswerNumber(int num) {
            this.correctAnswer = num;               //Sets correct Answer

        }

        public String getQuestionText() {
            return this.questionText;               //Returns Question Text
        }

        public String getPossibleAnswer(int num) {
            return this.possibleAnswers[num];       //Returns Possible Answer
        }

        public int getCorrectAnswerNumber() {
            return this.correctAnswer;              //Returns Correct Answer
        }

        public String getCorrectAnswer() {
            return this.possibleAnswers[this.correctAnswer];    //Returns Possible Answer
        }
    }

    public class Player {

        private int playerNumber;  // The player number
        private int points;        // Player's points
        private int currentAnswer; // Current chosen answer

        //Constructor
        public Player(int playerNum) {
            playerNumber = playerNum;
            points = 0;

        }

        public void chooseAnswer() {
            // Create a Scanner object for keyboard input.
            // Get the user's chosen answer.
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Please enter your Answer");    //Asks user for a number
            this.currentAnswer = keyboard.nextInt();

        }

        public int getCurrentAnswer() {
            return this.currentAnswer;          //Returns Current Answer

        }

        public void incrementPoints() {
            this.points++;                      //Increments the points

        }

        public int getPoints() {
            return this.points;                 //Returns the points

        }
    }
}

   

Was This Post Helpful? 0
  • +
  • -

#10 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,913
  • Joined: 06-March 08

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 08:46 PM

Good show :^: I'm impressed. You did it quite fast without giving me a -1. I appreciate.

You still want to use a Scanner to input your question or you want to use a GUI ?
Was This Post Helpful? 0
  • +
  • -

#11 Gijimu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-December 10

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 09:08 PM

GUI
Was This Post Helpful? 0
  • +
  • -

#12 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,913
  • Joined: 06-March 08

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 09:22 PM

View PostGijimu, on 01 December 2010 - 10:08 PM, said:

GUI

So you will need JTextField in your Window classes to input these questions
Was This Post Helpful? 0
  • +
  • -

#13 Gijimu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-December 10

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 09:36 PM

Something like this


JTextField name = new JTextField(30); name.setText("Type you name in this field"); 
name.getText();


Would I put it under the MyWindow class?
Was This Post Helpful? 0
  • +
  • -

#14 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8347
  • View blog
  • Posts: 31,913
  • Joined: 06-March 08

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 09:49 PM

View PostGijimu, on 01 December 2010 - 10:36 PM, said:

Something like this


JTextField name = new JTextField(30); name.setText("Type you name in this field"); 
name.getText();


Would I put it under the MyWindow class?

Yes and know :)

First you might want to associate a JLabel with a JTextField
JLabel nameLabel = new JLabel("Name: ");
JTextField nameText = new JTextField(80);
and manage to display them side by side

then you do not nameText.getName() right away. You wait for an event (like a button click) to retreive all the informations from the different JTextField

public void actionPerformed(ActionEvent e) {
   Object o = e.getSource();
   if(o == goButton) {
     name = nameText.getText();
     question1 = question1.getText();
     ....


Was This Post Helpful? 0
  • +
  • -

#15 Gijimu  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 11
  • Joined: 01-December 10

Re: GUI-based application for a Trivia game

Posted 01 December 2010 - 10:57 PM

I tried implementing that but errors were coming up but I did add the jfield and the jlabel parts to you showed me. I just keep on getting a one window pop up with nothing. Any clues?



import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;


public class TriviaGame {

    public static void main(String[] args) {
        TriviaGame triviaGame = new TriviaGame();


        MyWindow w = new MyWindow(Color.BLUE);
        w.setVisible(true);
        MyWindow c = new MyWindow(Color.RED);
        w.setVisible(true);

    }

    static void displayQuestion(EndingListener.Question question, int playerTurn) {
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

class MyWindow extends JFrame {

    public MyWindow(Color theColor) {
        super();
        setSize(300, 200);
        setTitle("Trivia Quest");
        setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        getContentPane().setBackground(theColor);

        JButton endButton = new JButton("Click to end program.");
        endButton.addActionListener((ActionListener) new EndingListener());
        add(endButton);


    }

}

//class EndingListener could have been a private inner class of MyWindow
class EndingListener implements ActionListener {

    private class NUM_PLAYER {

        public NUM_PLAYER() {
        }
    }

    private class i<T> {

        public i() {
        }
    }

    private class qArray {

        public qArray() {
        }
    }
    JLabel nameLabel = new JLabel("Name: ");
    JTextField nameText = new JTextField(80);






   
    public void actionPerformed(ActionEvent e) {

        System.exit(0);




        // Constants
        final int NUM_QUESTIONS = 5;
        final int NUM_PLAYERS = 1;

        // Variables
        int playerTurn = 1; // The current player
        int questionNum; // The current question number
        int playerAnswer; // The player's chosen answer
        int player1points = 0; // Player's points


        // Create an array of Player objects for player.
        Player[] p = new Player[NUM_PLAYERS];
        Player[] player = null;
        for (int i = 0; i < NUM_PLAYERS; i++) {
        }




        // Create an array to hold Question objects.
        Question[] questions = new Question[NUM_QUESTIONS];



        // Initialize the array with data.
        Question[] qArray = null;

        // Play the game.
        for (int i = 0; i < NUM_QUESTIONS; i++) {

            // Display the question.
            TriviaGame.displayQuestion(qArray[i], playerTurn);

            // Get the player's answer.
            player[playerTurn - 1].chooseAnswer();

            // See if the correct answer was chosen.
            if (qArray[i].getCorrectAnswerNumber()
                    == player[playerTurn - 1].getCurrentAnswer()) {

                player[playerTurn - 1].incrementPoints();

            }
            // See if the the player chose the wrong answer.
            // do nothing


        }
        // Show the game results.
        showGameResults(player);
        /**
         * The initQuestions method uses the contents of the trivia.text file to
         * populate the qArray parameter with Question objects.
         */
        class initQuestions {
        }
        // Open the trivia.txt file.
        File file = new File("trivia.txt");
        Scanner inputFile = null;

        try {
            inputFile = new Scanner(file);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(EndingListener.class.getName()).log(Level.SEVERE, null, ex);
        }

        // Populate the qArray with data from the file.
        for (int i = 0; i < qArray.length; i++) {



            // Get the question text from the file.
            qArray[i].setQuestion(inputFile.nextLine());

            // Get the possible answers.
            for (int j = 1; j <= 4; j++) {
                qArray[i].setPossibleAnswer(inputFile.nextLine(), j);

            }
            // Get the correct answer.
            qArray[i].setCorrectAnswerNumber(Integer.parseInt(inputFile.nextLine()));

        }


    }

    public void displayQuestion(Question q, int playerNum) {
        // Display the player number
        System.out.println("Question for player #" + playerNum);
        System.out.println("------------------------");

        // Display the question.
        System.out.println(q.getQuestionText());
        for (int i = 1; i <= 4; i++) {
            System.out.println(i + ". " + q.getPossibleAnswer(i));

        }
    }

    public void showGameResults(Player[] players) {
        // Display the stats.
        System.out.println("Game Over!");
        System.out.println("Player's points: " + players[0].getPoints());

        // Declare the winner.
        if (players[0].getPoints() > players[1].getPoints()) {
            System.out.println("Player wins!");
        }

    }

    public final class Question {
        // Constant for the number of answers

        public final int NUM_ANSWERS = 5;
        // The trivia question
        private String questionText;
        // An array to hold possible answers.
        private String possibleAnswers[] = new String[NUM_ANSWERS];
        // The number (1, 2, 3, or 4) of the correct answer.
        private int correctAnswer;

        //Constructor
        public Question() {
            // Initialize all fields to "" or 0;
            questionText = "";
            correctAnswer = 0;
            for (int i = 1; i < NUM_ANSWERS; i++) {
                setPossibleAnswer("", i);
            }


        }

        public void setQuestion(String question) {
            this.questionText = question;           //Sets the question

        }

        public void setPossibleAnswer(String text, int num) {
            this.possibleAnswers[num] = text;       //Sets possible Answer

        }

        public void setCorrectAnswerNumber(int num) {
            this.correctAnswer = num;               //Sets correct Answer

        }

        public String getQuestionText() {
            return this.questionText;               //Returns Question Text
        }

        public String getPossibleAnswer(int num) {
            return this.possibleAnswers[num];       //Returns Possible Answer
        }

        public int getCorrectAnswerNumber() {
            return this.correctAnswer;              //Returns Correct Answer
        }

        public String getCorrectAnswer() {
            return this.possibleAnswers[this.correctAnswer];    //Returns Possible Answer
        }
    }

    public class Player {

        private int playerNumber;  // The player number
        private int points;        // Player's points
        private int currentAnswer; // Current chosen answer

        //Constructor
        public Player(int playerNum) {
            playerNumber = playerNum;
            points = 0;

        }

        public void chooseAnswer() {
            // Create a Scanner object for keyboard input.
            // Get the user's chosen answer.
            Scanner keyboard = new Scanner(System.in);
            System.out.print("Please enter your Answer");    //Asks user for a number
            this.currentAnswer = keyboard.nextInt();

        }

        public int getCurrentAnswer() {
            return this.currentAnswer;          //Returns Current Answer

        }

        public void incrementPoints() {
            this.points++;                      //Increments the points

        }

        public int getPoints() {
            return this.points;                 //Returns the points

        }
    }
}

   

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2