CSC212: Computer Science.
TEXTBOOK: Object-Oriented Data Structures Using Java
TEXTBOOK: Source Code
|
//----------------------------------------------------------------------
// Date.java by Dale/Joyce/Weems Chapter 1
//
// Supports date objects having year, month, and day attributes.
//----------------------------------------------------------------------
public class Date
{
protected int year;
protected int month;
protected int day;
public static final int MINYEAR = 1583;
// Constructor
public Date(int newMonth, int newDay, int newYear)
{
month = newMonth;
day = newDay;
year = newYear;
}
// Observers
public int getYear()
{
return year;
}
public int getMonth()
{
return month;
}
public int getDay()
{
return day;
}
public int lilian()
{
// Returns the Lilian Day Number of this date.
// Precondition: This Date is a valid date after 10/14/1582.
//
// Computes the number of days between 1/1/0 and this date as if no calendar
// reforms took place, then subtracts 578,100 so that October 15, 1582 is day 1.
final int subDays = 578100; // number of calculated days from 1/1/0 to 10/14/1582
int numDays = 0;
// Add days in years.
numDays = year * 365;
// Add days in the months.
if (month <= 2)
numDays = numDays + (month - 1) * 31;
else
numDays = numDays + ((month - 1) * 31) - ((4 * (month-1) + 27) / 10);
// Add days in the days.
numDays = numDays + day;
// Take care of leap years.
numDays = numDays + (year / 4) - (year / 100) + (year / 400);
// Handle special case of leap year but not yet leap day.
if (month < 3)
{
if ((year % 4) == 0) numDays = numDays - 1;
if ((year % 100) == 0) numDays = numDays + 1;
if ((year % 400) == 0) numDays = numDays - 1;
}
// Subtract extra days up to 10/14/1582.
numDays = numDays - subDays;
return numDays;
}
public String toString()
// Returns this date as a String.
{
return(month + "/" + day + "/" + year);
}
}
|
|
//----------------------------------------------------------------------
// DaysBetween.java by Dale/Joyce/Weems Chapter 1
//
// Asks the user to enter two "modern" dates and then reports
// the number of days between the two dates.
//----------------------------------------------------------------------
import java.util.Scanner;
public class DaysBetween
{
public static void main(String[] args)
{
Scanner conIn = new Scanner(System.in);
int day, month, year;
System.out.println("Enter two 'modern' dates: month day year");
System.out.println("For example, January 12, 1954, would be: 1 12 1954");
System.out.println();
System.out.println("Modern dates occur after " + Date.MINYEAR + ".");
System.out.println();
System.out.println("Enter the first date:");
month = conIn.nextInt();
day = conIn.nextInt();
year = conIn.nextInt();
Date date1 = new Date(month, day, year);
System.out.println("Enter the second date:");
month = conIn.nextInt();
day = conIn.nextInt();
year = conIn.nextInt();
Date date2 = new Date(month, day, year);
if ((date1.getYear() <= Date.MINYEAR)
||
(date2.getYear() <= Date.MINYEAR))
System.out.println("You entered a 'pre-modern' date.");
else
{
System.out.println("The number of days between");
System.out.print(date1);
System.out.print(" and ");
System.out.print(date2);
System.out.print(" is ");
System.out.println(Math.abs(date1.lilian() - date2.lilian()));
}
}
}
|
|
public class Circle implements FigureGeometry
{
protected float radius;
protected int scale;
public Circle(float radius)
{
this.radius = radius;
}
public float perimeter()
// Returns perimeter of this figure.
{
return(2 * PI * radius);
}
public float area()
// Returns area of this figure.
{
return(PI * radius * radius);
}
public void setScale(int scale)
// Scale of this figure is set to "scale".
{
this.scale = scale;
}
public float weight()
// Precondition: Scale of this figure has been set.
//
// Returns weight of this figure. Weight = area X scale.
{
return(this.area() * scale);
}
}
|
|
public interface FigureGeometry
{
final float PI = 3.14f;
float perimeter();
// Returns perimeter of this figure.
float area();
// Returns area of this figure.
void setScale(int scale);
// Scale of this figure is set to "scale".
float weight();
// Precondition: Scale of this figure has been set.
//
// Returns weight of this figure. Weight = area X scale.
}
|
|
//----------------------------------------------------------------------------
// ITDArrayStringLog.java by Dale/Joyce/Weems Chapter 2
//
// Interactive Test Driver for the ArrayStringLog class
//----------------------------------------------------------------------------
import java.util.*;
import ch02.stringLogs.*;
public class ITDArrayStringLog
{
public static void main(String[] args)
{
ArrayStringLog test = new ArrayStringLog("Testing");
Scanner conIn = new Scanner(System.in);
String skip; // skip end of line after reading an integer
boolean keepGoing; // flag for "choose operation" loop
int constructor; // indicates user's choice of constructor
int operation; // indicates user's choice of operation
// Handle test name
System.out.println("What is the name of this test?");
String testName = conIn.nextLine();
System.out.println("\nThis is test " + testName + "\n");
// Handle constructor
System.out.println("Choose a constructor:");
System.out.println("1: ArrayStringLog(String name)");
System.out.println("2: ArrayStringLog(String name, int maxSize)");
if (conIn.hasNextInt())
constructor = conIn.nextInt();
else
{
System.out.println("Error: you must enter an integer.");
System.out.println("Terminating test.");
return;
}
skip = conIn.nextLine();
switch (constructor)
{
case 1:
test = new ArrayStringLog(testName);
break;
case 2:
System.out.println("Enter a maximum size:");
int maxSize;
if (conIn.hasNextInt())
maxSize = conIn.nextInt();
else
{
System.out.println("Error: you must enter an integer.");
System.out.println("Terminating test.");
return;
}
skip = conIn.nextLine();
test = new ArrayStringLog(testName, maxSize);
break;
default:
System.out.println("Error in constructor choice. Terminating test.");
return;
}
// Handle test cases
keepGoing = true;
while (keepGoing)
{
System.out.println("\nChoose an operation:");
System.out.println("1: insert(String element)");
System.out.println("2: clear()");
System.out.println("3: contains(String element)");
System.out.println("4: isFull()");
System.out.println("5: size()");
System.out.println("6: getName()");
System.out.println("7: show contents");
System.out.println("8: stop Testing");
if (conIn.hasNextInt())
operation = conIn.nextInt();
else
{
System.out.println("Error: you must enter an integer.");
System.out.println("Terminating test.");
return;
}
skip = conIn.nextLine();
switch (operation)
{
case 1: // insert
System.out.println("Enter string to insert:");
String insertString = conIn.nextLine();
test.insert(insertString);
break;
case 2: // clear
test.clear();
break;
case 3: // contains
System.out.println("Enter string to search for:");
String searchString = conIn.nextLine();
System.out.println("Result: " + test.contains(searchString));
break;
case 4: // isFull
System.out.println("Result: " + test.isFull());
break;
case 5: // size
System.out.println("Result: " + test.size());
break;
case 6: // getName
System.out.println("Result: " + test.getName());
break;
case 7: // show contents
System.out.println(test);
break;
case 8: // stop testing
keepGoing = false;
break;
default:
System.out.println("Error in operation choice. Terminating test.");
return;
}
}
System.out.println("End of Interactive Test Driver");
}
}
|
|
//----------------------------------------------------------------------
// ArrayStringLog.java by Dale/Joyce/Weems Chapter 2
//
// Implements StringLogInterface using an array to hold the strings.
//----------------------------------------------------------------------
package ch02.stringLogs;
public class ArrayStringLog implements StringLogInterface
{
protected String name; // name of this StringLog
protected String[] log; // array that holds strings
protected int lastIndex = -1; // index of last string in array
public ArrayStringLog(String name, int maxSize)
// Precondition: maxSize > 0
//
// Instantiates and returns a reference to an empty ArrayStringLog
// object with name "name" and room for maxSize strings.
{
log = new String[maxSize];
this.name = name;
}
public ArrayStringLog(String name)
// Instantiates and returns a reference to an empty ArrayStringLog
// object with name "name" and room for 100 strings.
{
log = new String[100];
this.name = name;
}
public void insert(String element)
// Precondition: This StringLog is not full.
//
// Places element into this StringLog.
{
lastIndex++;
log[lastIndex] = element;
}
public boolean isFull()
// Returns true if this StringLog is full, otherwise returns false.
{
if (lastIndex == (log.length - 1))
return true;
else
return false;
}
public int size()
// Returns the number of Strings in this StringLog.
{
return (lastIndex + 1);
}
public boolean contains(String element)
// Returns true if element is in this StringLog,
// otherwise returns false.
// Ignores case differences when doing string comparison.
{
int location = 0;
while (location <= lastIndex)
{
if (element.equalsIgnoreCase(log[location])) // if they match
return true;
else
location++;
}
return false;
}
public void clear()
// Makes this StringLog empty.
{
for (int i = 0; i <= lastIndex; i++)
log[i] = null;
lastIndex = -1;
}
public String getName()
// Returns the name of this StringLog.
{
return name;
}
public String toString()
// Returns a nicely formatted string representing this StringLog.
{
String logString = "Log: " + name + "\n\n";
for (int i = 0; i <= lastIndex; i++)
logString = logString + (i+1) + ". " + log[i] + "\n";
return logString;
}
}
|
|
//----------------------------------------------------------------------
// LinkedStringLog.java by Dale/Joyce/Weems Chapter 2
//
// Implements StringLogInterface using a linked list
// of LLStringNode to hold the log strings.
//----------------------------------------------------------------------
package ch02.stringLogs;
public class LinkedStringLog implements StringLogInterface
{
protected LLStringNode log; // reference to first node of linked
// list that holds the StringLog strings
protected String name; // name of this StringLog
public LinkedStringLog(String name)
// Instantiates and returns a reference to an empty StringLog object
// with name "name".
{
log = null;
this.name = name;
}
public void insert(String element)
// Precondition: This StringLog is not full.
//
// Places element into this StringLog.
{
LLStringNode newNode = new LLStringNode(element);
newNode.setLink(log);
log = newNode;
}
public boolean isFull()
// Returns true if this StringLog is full, false otherwise.
{
return false;
}
public int size()
// Returns the number of Strings in this StringLog.
{
int count = 0;
LLStringNode node;
node = log;
while (node != null)
{
count++;
node = node.getLink();
}
return count;
}
public boolean contains(String element)
// Returns true if element is in this StringLog,
// otherwise returns false.
// Ignores case difference when doing string comparison.
{
LLStringNode node;
node = log;
while (node != null)
{
if (element.equalsIgnoreCase(node.getInfo())) // if they match
return true;
else
node = node.getLink();
}
return false;
}
public void clear()
// Makes this StringLog empty.
{
log = null;
}
public String getName()
// Returns the name of this StringLog.
{
return name;
}
public String toString()
// Returns a nicely formatted string representing this StringLog.
{
String logString = "Log: " + name + "\n\n";
LLStringNode node;
node = log;
int count = 0;
while (node != null)
{
count++;
logString = logString + count + ". " + node.getInfo() + "\n";
node = node.getLink();
}
return logString;
}
}
|
|
//----------------------------------------------------------------------------
// LLStringNode.java by Dale/Joyce/Weems Chapter 2
//
// Implements String nodes for a Linked List.
//----------------------------------------------------------------------------
package ch02.stringLogs;
public class LLStringNode
{
private String info;
private LLStringNode link;
public LLStringNode(String info)
{
this.info = info;
link = null;
}
public void setInfo(String info)
// Sets info string of this LLStringNode.
{
this.info = info;
}
public String getInfo()
// Returns info string of this LLStringNode.
{
return info;
}
public void setLink(LLStringNode link)
// Sets link of this LLStringNode.
{
this.link = link;
}
public LLStringNode getLink()
// Returns link of this LLStringNode.
{
return link;
}
}
|
|
//----------------------------------------------------------------------
// StringLogInterface.java by Dale/Joyce/Weems Chapter 2
//
// Interface for a class that implements a log of Strings.
// A log "remembers" the elements placed into it.
//
// A log must have a "name".
//----------------------------------------------------------------------
package ch02.stringLogs;
public interface StringLogInterface
{
void insert(String element);
// Precondition: This StringLog is not full.
//
// Places element into this StringLog.
boolean isFull();
// Returns true if this StringLog is full, otherwise returns false.
int size();
// Returns the number of Strings in this StringLog.
boolean contains(String element);
// Returns true if element is in this StringLog,
// otherwise returns false.
// Ignores case differences when doing string comparison.
void clear();
// Makes this StringLog empty.
String getName();
// Returns the name of this StringLog.
String toString();
// Returns a nicely formatted string representing this StringLog.
}
|
|
//----------------------------------------------------------------------------
// Test034.java by Dale/Joyce/Weems Chapter 2
//
// Batch test case example
//----------------------------------------------------------------------------
import ch02.stringLogs.*;
public class Test034
{
public static void main(String[] args)
{
ArrayStringLog test = new ArrayStringLog("Test 34");
test.insert("trouble in the fields");
test.insert("love at the five and dime");
test.insert("once in a very blue moon");
if (test.contains("Love at the Five and Dime"))
System.out.println("Test 34 passed");
else
System.out.println("Test 34 failed");
}
}
|
|
General Trivia 1
4
6
Rock and Roll
Give the first name of one of The Beatles.
5
John
Paul
George
Ringo
Richard
Math
What is 5 + 2?
2
7
seven
History
Who was the second president of the USA?
2
Adams
John Adams
Vegetables
What color are carrots?
1
orange
|
|
//----------------------------------------------------------------------------
// GetTriviaGame.java by Dale/Joyce/Weems Chapter 2
//
// Provides methods that obtain information about a Trivia Game, create and
// return TriviaGame objects.
//
// Note: Currently only option is to obtain a game from a text file, but
// other options could be added later.
//----------------------------------------------------------------------------
import java.util.*;
import java.io.*;
public class GetTriviaGame
{
public static TriviaGame useTextFile(String textfile)throws IOException
// Precondition: The textfile exists and contains a correctly formatted game.
{
TriviaGame game;
String quizName;
int numQuestions;
int numChances;
// for a specific trivia question
TriviaQuestion tq;
String category;
String question;
String answer;
int numAnswers;
FileReader fin = new FileReader(textfile);
Scanner triviaIn = new Scanner(fin);
String skip; // skip end of line after reading integer
// Scan in basic trivia quiz information and set variables.
quizName = triviaIn.nextLine();
numQuestions = triviaIn.nextInt();
numChances = triviaIn.nextInt();
skip = triviaIn.nextLine();
// Instantiate the Trivia Game.
game = new TriviaGame(quizName, numQuestions, numChances);
// Scan in and set up the questions and answers.
for (int i = 1; i <= numQuestions; i++)
{
category = triviaIn.nextLine();
question = triviaIn.nextLine();
numAnswers = triviaIn.nextInt();
skip = triviaIn.nextLine();
tq = new TriviaQuestion(category, question, numAnswers);
for (int j = 1; j <= numAnswers; j++)
{
answer = triviaIn.nextLine();
tq.storeAnswer(answer);
}
game.insertQuestion(tq);
}
return game;
}
}
|
|
General Trivia 2
7
9
Rock and Roll
Name the first name of one of the Fab Four.
4
John
Paul
George
Ringo
Math
What is 5 + 2?
2
7
seven
History
Who was the second president of the USA?
2
Adams
John Adams
Vegetables
What color are carrots?
1
orange
Technology
What sort of information is held in an MP3 file?
4
music
songs
audio
sound
Literature
Who wrote The Mythical Man-Month?
5
Fred Brooks
Brooks
Frederick Brooks
Frederick P Brooks
Frederick P. Brooks
Geography
On what continent will you find Vicoria Falls?
1
Africa
|
|
//----------------------------------------------------------------------
// TriviaConsole.java by Dale/Joyce/Weems Chapter 2
//
// Allows the user to play a trivia game.
// Uses a Console interface.
//----------------------------------------------------------------------
import java.io.*;
import java.util.Scanner;
public class TriviaConsole
{
public static void main(String[] args) throws IOException
{
Scanner conIn = new Scanner(System.in);
TriviaGame game; // the trivia game
int questNum; // current question number
TriviaQuestion tq; // current question
String answer; // answer provided by user
// Initialze the game
game = GetTriviaGame.useTextFile("game.txt");
// Greet the user.
System.out.println("Welcome to the " + game.getQuizName() + " trivia quiz.");
System.out.print("You will have " + game.getNumChances() + " chances ");
System.out.println("to answer " + game.getCurrNumQuestions() + " questions.\n");
questNum = 0;
while (!game.isOver())
{
// Get number of next unanswered question.
do
if (questNum == game.getCurrNumQuestions())
questNum = 1;
else
questNum = questNum + 1;
while (game.isAnswered(questNum));
// Ask question and handle user's response.
tq = game.getTriviaQuestion(questNum);
System.out.println(tq.getCategory() + ": " + tq.getQuestion());
answer = conIn.nextLine();
if (tq.tryAnswer(answer))
{
System.out.println("Correct!\n");
game.correctAnswer(questNum);
}
else
{
System.out.println("Incorrect\n");
game.incorrectAnswer();
}
}
System.out.println("\nGame Over");
System.out.println("\nResults:");
System.out.print(" Chances used: " + (game.getNumChances() - game.getRemainingChances()));
System.out.println(" Number Correct: " + game.getNumCorrect());
System.out.println("\nThank you.\n");
}
}
|
|
//----------------------------------------------------------------------------
// TriviaGame.java by Dale/Joyce/Weems Chapter 2
//
// Provides trivia game objects.
//----------------------------------------------------------------------------
public class TriviaGame
{
private String quizName;
private int maxNumQuestions;
private int numChances;
private int remainingChances;
private int numCorrect = 0;
private int numIncorrect = 0;
private TriviaQuestion[] questions; // the set of questions
private boolean[] correct; // true if corresponding question answered
private int currNumQuestions = 0; // current number of questions
public TriviaGame(String quizName, int maxNumQuestions, int numChances)
// Precondition: maxNumQuestions > 0 and numChances > 0
{
this.quizName = quizName;
this.maxNumQuestions = maxNumQuestions;
this.numChances = numChances;
remainingChances = numChances;
questions = new TriviaQuestion[maxNumQuestions];
correct = new boolean[maxNumQuestions];
}
public String getQuizName()
{
return quizName;
}
public int getNumChances()
{
return numChances;
}
public int getRemainingChances()
{
return remainingChances;
}
public int getNumCorrect()
{
return numCorrect;
}
public int getNumIncorrect()
{
return numIncorrect;
}
public int getCurrNumQuestions()
{
return currNumQuestions;
}
public TriviaQuestion getTriviaQuestion(int questionNumber)
// Precondition: 0 < questionNumber <= currNumQuestions
{
return questions[questionNumber - 1];
}
public boolean isAnswered(int questionNumber)
// Precondition: 0 < questionNumber <= currNumQuestions
{
return correct[questionNumber - 1];
}
public boolean isOver()
// Returns true if this game is over, false otherwise.
{
return (numCorrect == currNumQuestions)
||
(remainingChances <= 0);
}
public void insertQuestion(TriviaQuestion question)
// Precondition: currNumQuestions < maxNumQuestions
//
// Adds question to this TriviaGame.
{
questions[currNumQuestions] = question;
correct[currNumQuestions] = false;
currNumQuestions = currNumQuestions + 1;
}
public void correctAnswer(int questionNumber)
// Preconditions: 0 < questionNumber < maxNumQuestions
//
// Updates game status to indicate that question number
// "questionNumber" was answered correctly.
{
correct[questionNumber - 1] = true;
numCorrect = numCorrect + 1;
remainingChances = remainingChances - 1;
}
public void incorrectAnswer()
// Updates game status to indicate that a question
// was answered incorrectly
{
numIncorrect = numIncorrect + 1;
remainingChances = remainingChances - 1;
}
}
|
|
//*******
//
// TriviaGameGUI.java
//
//*******
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class TriviaGameGUI extends JPanel
{
JPanel titlePanel = new JPanel();
JPanel statusPanel = new JPanel();
JPanel choosePanel = new JPanel();
JPanel categoryPanel = new JPanel();
JPanel askPanel = new JPanel();
JPanel questionPanel = new JPanel();
JPanel enterAnswerPanel = new JPanel();
JPanel answerPanel = new JPanel();
JPanel submitPanel = new JPanel();
JPanel nextPanel = new JPanel();
JLabel titleLabel = new JLabel();
JLabel correctLabel = new JLabel();
JLabel incorrectLabel = new JLabel();
JLabel remainingLabel = new JLabel();
JLabel chooseLabel = new JLabel();
JLabel askLabel = new JLabel();
JLabel questionLabel = new JLabel();
JLabel enterAnswerLabel = new JLabel();
JLabel submitLabel = new JLabel();
JLabel resultLabel = new JLabel();
JLabel nextLabel = new JLabel();
JButton askButton = new JButton();
JButton submitButton = new JButton();
JButton nextButton = new JButton();
JRadioButton[] categories;
ButtonGroup catGroup = new ButtonGroup();
JTextField answerTextField = new JTextField(30);
TriviaGame game;
// Obtains game info and creates the screen
public TriviaGameGUI(TriviaGame game)
{
// choosePanel.setBackground(new Color(0,122,0)); do I want to do this??
this.game = game;
// set panel layouts
titlePanel.setLayout(new FlowLayout());
statusPanel.setLayout(new FlowLayout(FlowLayout.CENTER, 50, 0));
choosePanel.setLayout(new FlowLayout(FlowLayout.LEFT));
categoryPanel.setLayout(new GridLayout(0, 4));
askPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
questionPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
enterAnswerPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
submitPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
nextPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
// set Label fonts
Font quizBigFont = new Font("Helvetica Bold", Font.BOLD, 30);
Font quizMidFont = new Font("Helvetica Bold", Font.BOLD, 20);
Font quizSmallFont = new Font("Helvetica Bold", Font.BOLD, 15);
titleLabel.setFont(quizBigFont);
correctLabel.setFont(quizMidFont);
incorrectLabel.setFont(quizMidFont);
remainingLabel.setFont(quizMidFont);
chooseLabel.setFont(quizSmallFont);
askLabel.setFont(quizSmallFont);
questionLabel.setFont(quizSmallFont);
enterAnswerLabel.setFont(quizSmallFont);
submitLabel.setFont(quizSmallFont);
resultLabel.setFont(quizSmallFont);
nextLabel.setFont(quizSmallFont);
// set non game status text values
chooseLabel.setText("1. Choose a category:");
askLabel.setText("2. ");
askButton.setText("Submit category");
questionLabel.setText("3. Question:");
enterAnswerLabel.setText("4. Answer:");
submitLabel.setText("5. ");
submitButton.setText("Submit Answer");
resultLabel.setText(" ");
nextLabel.setText("6. ");
nextButton.setText(" Next ");
// set question category buttons; assumes there is at least one question
TriviaQuestion tq;
int numQuestions = game.getCurrNumQuestions();
categories = new JRadioButton[numQuestions];
tq = game.getTriviaQuestion(1);
categories[0] = new JRadioButton(tq.getCategory(),true);
categoryPanel.add(categories[0]);
catGroup.add(categories[0]);
for (int i = 2; i <= numQuestions; i++)
{
tq = game.getTriviaQuestion(i);
categories[i-1] = new JRadioButton(tq.getCategory());
categoryPanel.add(categories[i-1]);
catGroup.add(categories[i-1]);
}
// set game status text values
setGameValues();
// add info to panels
titlePanel.add(titleLabel);
statusPanel.add(correctLabel);
statusPanel.add(incorrectLabel);
statusPanel.add(remainingLabel);
choosePanel.add(chooseLabel);
choosePanel.add(categoryPanel);
askPanel.add(askLabel);
askButton.addActionListener(new askButton());
askPanel.add(askButton);
questionPanel.add(questionLabel);
enterAnswerPanel.add(enterAnswerLabel);
enterAnswerPanel.add(answerTextField);
submitPanel.add(submitLabel);
submitButton.addActionListener(new submitButton());
submitPanel.add(submitButton);
submitPanel.add(resultLabel);
nextButton.addActionListener(new nextButton());
nextPanel.add(nextLabel);
nextPanel.add(nextButton);
// build overall interface
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
add(titlePanel);
add(statusPanel);
add(choosePanel);
add(askPanel);
add(questionPanel);
add(enterAnswerPanel);
add(answerPanel);
add(submitPanel);
add(nextPanel);
}
public void display(int height)
{
JFrame theFrame = new JFrame("Trivia Game");
theFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theFrame.setContentPane(this);
theFrame.setPreferredSize(new Dimension(600, height));
theFrame.pack();
theFrame.setVisible(true);
}
private void setGameValues()
{
titleLabel.setText("Quiz: " + game.getQuizName());
correctLabel.setText("Correct: " + game.getNumCorrect());
incorrectLabel.setText("Incorrect: " + game.getNumIncorrect());
remainingLabel.setText("Remaining Chances: " + game.getRemainingChances());
// disable category buttons of answered questions and
// select first available button
boolean first = true;
int numQuestions = game.getCurrNumQuestions();
for (int i = 1; i <= numQuestions; i++)
if (game.isAnswered(i))
categories[i-1].setEnabled(false);
else
if (first)
{
categories[i-1].setSelected(true);
first = false;
}
}
class askButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
TriviaQuestion tq;
int numQuestions = game.getCurrNumQuestions();
int selectedIndex = -1;
for (int i = 0; i < numQuestions; i++)
{
if (categories[i].isSelected())
selectedIndex = i;
}
tq = game.getTriviaQuestion(selectedIndex + 1);
questionLabel.setText("3. Question: " + tq.getQuestion());
}
}
class submitButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
TriviaQuestion tq;
int numQuestions = game.getCurrNumQuestions();
int selectedIndex = -1;
for (int i = 0; i < numQuestions; i++)
{
if (categories[i].isSelected())
selectedIndex = i;
}
tq = game.getTriviaQuestion(selectedIndex + 1);
if (tq.tryAnswer(answerTextField.getText()))
{
resultLabel.setText(" Correct");
game.correctAnswer(selectedIndex + 1);
}
else
{
resultLabel.setText(" Incorrect");
game.incorrectAnswer();
}
}
}
class nextButton implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
setGameValues();
questionLabel.setText("3. Question: ");
resultLabel.setText("");
answerTextField.setText("");
}
}
}
|
|
//----------------------------------------------------------------------
// TriviaGUI.java by Dale/Joyce/Weems Chapter 2
//
// Allows the user to play a trivia game.
// Uses a GUI interface.
//----------------------------------------------------------------------
import java.io.*;
public class TriviaGUI
{
public static void main(String[] args) throws IOException
{
int numQuestions;
int height;
TriviaGame game; // the trivia game
// Initialze the game
game = GetTriviaGame.useTextFile("game.txt");
TriviaGameGUI gameGUI = new TriviaGameGUI(game);
numQuestions = game.getCurrNumQuestions();
height = 300 + (80 * (numQuestions / 4));
gameGUI.display(height);
}
}
|
|
//----------------------------------------------------------------------------
// TriviaQuestion.java by Dale/Joyce/Weems Chapter 2
//
// Provides trivia question objects.
//----------------------------------------------------------------------------
import ch02.stringLogs.*;
public class TriviaQuestion
{
private String category; // category of question
private String question; // the question
private StringLogInterface answers; // acceptable answers
public TriviaQuestion(String category, String question, int maxNumAnswers)
// Precondition: maxNumAnswers > 0
{
this.category = category;
this.question = question;
answers = new ArrayStringLog("trivia", maxNumAnswers);
}
public String getCategory()
{
return category;
}
public String getQuestion()
{
return question;
}
public boolean tryAnswer(String answer)
{
return answers.contains(answer);
}
public void storeAnswer(String answer)
// Precondition: answers String Log is not full
{
answers.insert(answer);
}
}
|
|
public class UseFigs
{
public static void main(String[] args)
{
Circle myCircle = new Circle(5);
System.out.println(myCircle.perimeter());
System.out.println(myCircle.area());
Rectangle myRectangle = new Rectangle(7, 8);
System.out.println(myRectangle.perimeter());
System.out.println(myRectangle.area());
}
}
|
|
//----------------------------------------------------------------------------
// UseStringLog.java by Dale/Joyce/Weems Chapter 2
//
// Simple example of the use of a StringLog.
//----------------------------------------------------------------------------
import ch02.stringLogs.*;
public class UseStringLog
{
public static void main(String[] args)
{
StringLogInterface sample;
sample = new ArrayStringLog("Example Use");
sample.insert("Elvis");
sample.insert("King Louis XII");
sample.insert("Captain Kirk");
System.out.println(sample);
System.out.println("The size of the log is " + sample.size());
System.out.println("Elvis is in the log: " + sample.contains("Elvis"));
System.out.println("Santa is in the log: " + sample.contains("Santa"));
}
}
|