CS249 – Java
Object Oriented Programming
Instructor: Rosemary Mullick, Ph.D.
Menu:
- Calculate Commuter Costs
- Track Fuel & Milage
- Tic-Tac-Toe Game
- Movie Rental Program
- Contact List
- Decimal to Binary Converter (SWING)
- Tic-Tac-Toe Game (SWING)
- Change Font Style, Size, & Color (SWING)
Calculate Commuter Costs:
/*
File: ghp1.java
By: Ronny L. Bull
Date: 5-10-2010
Problem: Savitch "Absolute Java" Ch 2 pg 91 problem 4
Descripton: This program computes the cost of a commute.
Precondition: User inputs distance of commute in miles, price of a gallon of gas, and vehicle's MPG.
Postconditon: Output cost of commute
*/
/*
Dictonary of Variables:
dist; float, distance of commute
price; float, cost of a gallon of gas
mpg; float, vehicles miles pet gallon
cost; float, total cost of the commute
*/
import java.util.Scanner; //Import Scanner utility
//Define the class
public class ghp1
{
//Main
public static void main(String[] args)
{
//Setup keyboard input scanner
Scanner keyboard = new Scanner(System.in);
//Prompt user for distance
System.out.println("Please enter the distance of the commute in miles. ");
//Store in dist
float dist = keyboard.nextFloat();
//Prompt user for price
System.out.println("Please enter the price of a gallon of gas. ");
//Store in price
float price = keyboard.nextFloat();
//Prompt user for vehicle MPG
System.out.println("Please enter the vehicles MPG. ");
//Store in mpg
float mpg = keyboard.nextFloat();
//Do calculation
float cost = dist/mpg * price;
//Output the commute cost
System.out.printf("The total cost of the commute is $%4.2f \n", cost);
}
}
Track Fuel & Milage:
ghp2.java
/*
File: ghp2.java
By: Ronny L. Bull
Date: 5-11-2010
Problem: Savitch "Absolute Java" Ch 4 pg 247 problem 3
Descripton: Driver program for Odometer class
Precondition: Creates an instance of the class Odometer
Postconditon:
Resets the Odometer to 0 with the setResetMiles mutator method
Adds miles to the current Odometer with the setAddMiles mutator method
Sets the current vehicle's fuel efficiency with the setMpg mutator method
Returns the fuel used in gallons with the getFuelUsed accessor method
Returns the current Odometer reading with the getOdometer accessor method
Returns the current MPG setting with the getMpg accessor method
*/
/*
Dictonary of Variables:
myMiles; float, stores user input of miles
myMpg; float, stores user input of fuel efficiency
myReset; string, used to check if the odometer should be reset
i; int, loop counter
j; int, trip counter
*/
import java.util.Scanner; //Import Scanner utility
//Main
public class ghp2
{
public static void main(String[] args)
{
float myMiles;
float myMpg;
String myReset;
int i = 0;
int j;
//Setup keyboard input scanner
Scanner keyboard = new Scanner(System.in);
//Create an object called od of class Odometer
Odometer od = new Odometer();
//Output to user program description
System.out.println("This program allows a user to track fuel consumption over a series of 5 trips");
System.out.println("");
System.out.println("***Program Begins***");
System.out.println("");
//Start do-while loop for 5 trips
do
{
//Output trip number
j = i+1;
System.out.println("Trip " + j);
System.out.println("");
//Prompt user to reset Odometer
od.getOdometer();
System.out.println("Would you like to reset the current Odometer? (y/n)");
myReset = keyboard.next();
//If "y" then reset the Odometer else move on
if(myReset.equalsIgnoreCase("y"))
{
od.setResetOdometer();
System.out.println("The Odometer has been reset.");
}
//Output current Odometer reading
od.getOdometer();
System.out.println("");
//Prompt user to add miles
System.out.println("Please enter the number of miles you would like to add to the current Odometer.");
myMiles = keyboard.nextFloat();
od.setAddMiles(myMiles);
od.getOdometer();
System.out.println("");
//Prompt user to set MPG
System.out.println("Please enter the vehicle's fuel efficiency in miles per gallon.");
myMpg = keyboard.nextFloat();
od.setMpg(myMpg);
od.getMpg();
System.out.println("");
//Output gallons consumed
System.out.println("********************************************************************");
System.out.println("Total gasoline consumption in gallons since the last Odometer reset:");
od.getFuelUsed();
System.out.println("********************************************************************");
System.out.println("");
//Increase i by 1
i++;
}
while(i < 5); //Check for 5 passes
//Output that the program has ended
System.out.println("***Program Ends***");
}
}
Odometer.java
/*
File: Odometer.java
By: Ronny L. Bull
Date: 5-11-2010
Problem: Savitch "Absolute Java" Ch 4 pg 247 problem 3
Descripton: Class used to track fuel and mileage for an automobile
Precondition: invoked by class ghp2
Postconditon:
Resets curOdometer to 0
Adds miles to curOdometer
Sets mpg
Outputs fuel consumption
Outputs mpg
Outputs curOdometer
*/
/*
Dictonary of Variables:
miles; float, user entered miles
mpg; float, user entered fuel efficiency
curOdometer; float, current odometer reading
*/
//Define the class
public class Odometer
{
//Instance Variables
private float curOdometer = 0;
private float miles = 0;
private float mpg = 0;
//Mutator Methods
//setResetMiles
//Precondition: Invoked by ghp2
//Postcondition: Resets the odometer to 0
public void setResetOdometer()
{
this.curOdometer = 0;
}
//setMpg
//Precondition: User inputs fuel efficiency
//Postcondition: input is stored in mpg
public void setMpg(float mpg)
{
this.mpg = mpg;
}
//setAddMiles
//Precondition: User inputs miles to be added to current odometer
//Postcondition: input is stored in miles
public void setAddMiles(float miles)
{
this.curOdometer = curOdometer + miles;
}
//Accessor Methods
//getFuelUsed
//Precondition: Invoked by ghp2
//Postcondition: Outputs fuel consumption since last odometer reset
public void getFuelUsed()
{
//Calculate: gallons = Odometer / efficiency
System.out.println(curOdometer / mpg + " Gallons");
}
//getOdometer
//Precondition: Invoked by ghp2
//Postcondition: Returns curOdometer value
public void getOdometer()
{
System.out.println("Current Odometer: " + curOdometer);
}
//getMpg
//Precondition: Invoked by ghp2
//Postcondition: Returns mpg value
public void getMpg()
{
System.out.println("Current Fuel Efficiency: " + mpg + " MPG");
}
}
Tic-Tac-Toe Game:
ghp3.java
/*
File: ghp3.java
By: Ronny L. Bull
Date: 5-15-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 6 pg 416 problem 10
Descripton: Driver program for Tic-Tac-Toe game
Precondition: Creates an instance of the class Control
Postconditon:
Initializes the game board
Prompts player to choose a mark
Sets an X or Y on the chosen mark
Prints the updated board after each turn
*/
/*
Dictonary of Variables:
myMark; char, stores players mark spot choice
line; string, stores keyboard input string
*/
import java.util.Scanner; //Import Scanner utility
//Main
public class ghp3
{
public static void main(String[] args)
{
//Setup keyboard input scanner
Scanner keyboard = new Scanner(System.in);
//Variables
char myMark;
String line;
//Create an object called ctrl of class Control
Control ctrl = new Control();
//Welcome the user
System.out.println("Welcome to Tic-Tac-Toe!");
System.out.println("");
//Setup and display the initial game board
System.out.println("Constructing the initial game board...");
System.out.println("");
ctrl.setBoard();
ctrl.getBoard();
System.out.println("");
//Game Loop - 9 spaces so 9 turns
for(int i=0;i<9;i++)
{
//Prompt for Player
ctrl.getPlayer();
System.out.println("Please choose a number on the board to place your mark.");
//Notes on character input:
//Trying to figure out proper way to read in a character
//Internet says to use: myMark = (char) System.in.read();
//However, I recieved errors and wasted a lot of time trying to get it to work.
//keyboard.nextChar() does not work, and keyboard.next() only works for strings
//So I found the following on page 277 in the book and it worked for me!
//Adapted from: Savitch "Absolute Java" pg 277
//Adapted by: Ronny L. Bull
//Date: 5-15-2010
line = keyboard.nextLine();
myMark = line.charAt(0);
//Set the player's mark on the board
ctrl.setMark(myMark);
//Display the changed board
System.out.println("");
ctrl.getBoard();
//Set the next player
System.out.println("");
ctrl.setPlayer();
}
//Game Over
System.out.println("Game Over!");
}
}
Control.java
/*
File: Control.java
By: Ronny L. Bull
Date: 5-15-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 6 pg 416 problem 10
Descripton: Class used to control a game of tic-tac-toe
Precondition: invoked by class ghp3
Postconditon:
Sets up initial game board
Rotates players
Marks the board with an X or O
Displays updated game board
Displays current player
*/
/*
Dictonary of Variables:
board; char, array that is used as the tic-tac-toe board
mark; char, players chosen point in the 2d array
i; int, loop counter
row; int, row counter
col; int, column counter
player; int, current player (initialized to 1)
*/
//Define the class
public class Control
{
//Instance Variables
char[][] board = new char[3][3]; //2D array
private int player = 1;
private char mark;
//Mutator Methods
//setBoard
//Precondition: Invoked by ghp3
//Postcondition: Sets up the initial board
public void setBoard()
{
board[0][0] = '1';
board[0][1] = '2';
board[0][2] = '3';
board[1][0] = '4';
board[1][1] = '5';
board[1][2] = '6';
board[2][0] = '7';
board[2][1] = '8';
board[2][2] = '9';
}
//setPlayer
//Precondition: invoked by ghp3
//Postcondition: sets the current player
public void setPlayer()
{
if(player == 1)
player=2;
else
player=1;
}
//setMark
//Precondition: Invoked by ghp3
//Postcondition: Sets an X or Y on the board (P1 = X, P2 = Y)
public void setMark(char mark)
{
this.mark = mark;
//Loop through the array
//Code adapted from: Savitch "Absolute Java" pg 396
//Adapted by: Ronny L. Bull
//Date: 5-15-2010
int row,col;
int i=0;
for(row=0; row < board.length; row++)
for(col=0; col < board[row].length; col++)
if(board[row][col]==mark)
{
//No Cheatin'!
if(mark != 'X' && mark != 'Y')
{
if(player==1)
board[row][col] = 'X';
if(player==2)
board[row][col] = 'Y';
}
else
{
System.out.println("Cheater! You may only enter a number that is currently on the board!");
System.out.println("Your devious ways have caused you to forefit this turn!");
return;
}
}
}
//Accessor Methods
//getBoard
//Precondition: Invoked by ghp3
//Postcondition: Displays the current game board
public void getBoard()
{
//Loop through the array
//Code adapted from: Savitch "Absolute Java" pg 396
//Adapted by: Ronny L. Bull
//Date: 5-15-2010
int row,col;
int i=0;
for(row=0; row < board.length; row++)
for(col=0; col < board[row].length; col++)
{
System.out.print(board[row][col] + " ");
i++;
if(i==3)
{
System.out.println("");
i=0;
}
}
}
//getPlayer
//Precondition: Invoked by ghp3
//Postcondition: Displays the current player
public void getPlayer()
{
if(player == 1)
System.out.println("Player 1");
else
System.out.println("Player 2");
}
}
Movie Rental Program:
ghp4.java
/*
File: ghp4.java
By: Ronny L. Bull
Date: 5-25-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 8 pg 509 problem 2
Descripton: Driver program for movie rental program
Precondition: Creates an instance of the class Movie
Postconditon:
Provides a main menu to choose options from
Allows a user to input a movie title
Allows a user to input a movie MPAA rating
Allows a user to input a movie ID number
Returns movie title
Returns movie MPAA rating
Returns movie ID number
Allows a user to compare two video ID number to see if they are equal
Allows a user to process late fees based on video type
*/
/*
Dictonary of Variables:
myTitle; String, user supplied movie title
myRating; String, user supplied movie MPAA rating
myID; int, user supplied movie ID number
myID1, myID2; int, user supplied movie ID numbers to compare
myDays; int, user supplied late days
choice; int, menu choice
videoType; int, menu choice
*/
import java.util.Scanner; //Import Scanner utility
//Main
public class ghp4
{
public static void main(String[] args)
{
//Setup keyboard input scanner
Scanner keyboard = new Scanner(System.in);
//Variables
String myTitle;
String myRating;
int myID, myID1, myID2;
int myDays;
int choice = 0;
int videoType = 0;
//Create an object called movie of class Movie
Movie movie = new Movie();
//Welcome the user
System.out.println("Welcome to Ronny's Video Rental Business");
System.out.println("");
//Loop until exit (4) is chosen
while(choice != 4)
{
//Main Menu
System.out.println("** Main Menu **");
System.out.println("What would you like to do?");
System.out.println("1. Enter a new video into the system");
System.out.println("2. Compare 2 video ID's to see if they are equal");
System.out.println("3. Calculate late fees");
System.out.println("4. Exit");
//Prompt user for menu choice
System.out.println("Please enter the number of your choice: ");
choice = keyboard.nextInt();
//Process choice
if(choice == 1)
{
//Prompt for movie title and store in myTitle
System.out.println("Please enter a movie title");
myTitle = keyboard.next();
movie.setTitle(myTitle);
//Prompt for movie rating and store in myRating
System.out.println("Please enter the movie's MPAA rating");
myRating = keyboard.next();
movie.setRating(myRating);
//Prompt for movie ID number and store in myID
System.out.println("Please enter the movie's ID number");
myID = keyboard.nextInt();
movie.setID(myID);
//Output results
System.out.println("The video has been entered as: ");
System.out.println("Title: " + movie.getTitle());
System.out.println("Rating: " + movie.getRating());
System.out.println("ID: " + movie.getID());
System.out.println("");
}
else if(choice == 2)
{
//Compare two video ID's to see if they are the same
System.out.println("Please enter the ID for movie 1");
myID1 = keyboard.nextInt();
System.out.println("Please enter the ID for movie 2");
myID2 = keyboard.nextInt();
movie.equals(myID1, myID2);
System.out.println("");
}
else if(choice == 3)
{
//Late fee processing
System.out.println("Please enter the number of days the video was late");
myDays = keyboard.nextInt();
//Video category selection
System.out.println("Please choose the type of video");
System.out.println("1. Action");
System.out.println("2. Comedy");
System.out.println("3. Drama");
System.out.println("4. Default");
videoType = keyboard.nextInt();
//Process choice
if(videoType == 1)
{
//Action fee
Action.calcLateFees(myDays);
}
else if(videoType == 2)
{
//Comedy fee
Comedy.calcLateFees(myDays);
}
else if(videoType == 3)
{
//Drama fee
Drama.calcLateFees(myDays);
}
else
{
//Default fee
movie.calcLateFees(myDays);
}
System.out.println("");
}
else if(choice == 4)
{
//Exit
System.out.println("Exiting...");
return;
}
else
{
//Invalid choice
System.out.println("You have entered an invalid choice");
System.out.println("Please try again");
System.out.println("");
}
}
}
}
Action.java
/*
File: Action.java
By: Ronny L. Bull
Date: 5-25-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 8 pg 509 problem 2
Descripton: Class for Action videos
Precondition: Creates an instance of the class Action derived from the class Movie
Postconditon:
Calculates the late fee for an action video
*/
/*
Dictonary of Variables:
*/
//Define the class
public class Action extends Movie
{
//Instance Variables
//Mutator Methods
//calcLateFees
//precondition: invoked by ghp4
//postcondition: returns the late fee amount using the Action video value of $3.00 per day
public static void calcLateFees(int days)
{
double lateFee = 3.00 * days;
System.out.printf("Late fees due: $%4.2f\n", lateFee);
}
//Accessor Methods
}
Comedy.java
/*
File: Comedy.java
By: Ronny L. Bull
Date: 5-25-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 8 pg 509 problem 2
Descripton: Class for Comedy videos
Precondition: Creates an instance of the class Comedy derived from the class Movie
Postconditon:
Calculates the late fees for a comedy video
*/
/*
Dictonary of Variables:
*/
//Define the class
public class Comedy extends Movie
{
//Instance Variables
//Mutator Methods
//calcLateFees
//precondition: invoked by ghp4
//postcondition: returns the late fee amount using the Comedy video value of $2.50 per day
public static void calcLateFees(int days)
{
double lateFee = 2.50 * days;
System.out.printf("Late fees due: $%4.2f\n", lateFee);
}
//Accessor Methods
}
Drama.java
/*
File: Drama.java
By: Ronny L. Bull
Date: 5-25-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 8 pg 509 problem 2
Descripton: Class for Drama videos
Precondition: Creates an instance of the class Drama derived from the class Movie
Postconditon:
Calculates the late fee for a drama video
*/
/*
Dictonary of Variables:
*/
//Define the class
public class Drama extends Movie
{
//Instance Variables
//Mutator Methods
//calcLateFees
//precondition: invoked by ghp4
//postcondition: returns the late fee amount using the Drama video value of $2.00 per day
public static void calcLateFees(int days)
{
double lateFee = 2.00 * days;
System.out.printf("Late fees due: $%4.2f\n", lateFee);
}
//Accessor Methods
}
Movie.java
/*
File: Movie.java
By: Ronny L. Bull
Date: 5-25-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 8 pg 509 problem 2
Descripton: Class used to track the MPAA Rating, ID number, and movie title of a video.
Precondition: Creates an instance of the class Movie
Postconditon:
Sets Video Title
Sets Video MPAA Rating
Sets Video ID Number
Displays Video Title
Displays Video MPAA Rating
Displays Video ID Number
Checks to see if two movies are equal by ID
Calculates late fees using a default value of $2.00
*/
/*
Dictonary of Variables:
title; String, movie title
rating; String, movie MPAA rating
id; int, movie ID number
lateFee; double, late fee amount
days; int, days late
*/
//Define the class
public class Movie
{
//Instance Variables
private String title;
private String rating;
private int id;
//Mutator Methods
//setTitle
//precondition: invoked by ghp4
//postcondition: sets the movie title
public void setTitle(String title)
{
this.title = title;
}
//setRating
//precondition: invoked by ghp4
//postcondition: sets the movie MPAA rating
public void setRating(String rating)
{
this.rating = rating;
}
//setID
//precondition: invoked by ghp4
//postcondition: sets the movie ID number
public void setID(int id)
{
this.id = id;
}
//calcLateFees
//precondition: invoked by ghp4
//postcondition: returns the late fee amount using the default value of $2.00 per day
public static void calcLateFees(int days)
{
double lateFee = 2.00 * days;
System.out.printf("Late fees due: $%4.2f\n", lateFee);
}
//equals method
//precondition: invoked by ghp4
//postcondition: checks to see if two movies are equal by their ID numbers
public void equals(int id1, int id2)
{
if(id1 == id2)
System.out.println("The movies are the same.");
else
System.out.println("The movies are not the same.");
}
//Accessor Method
//getTitle
//precondition: invoked by ghp4
//postcondition: returns the movie title
public String getTitle()
{
return title;
}
//getRating
//precondition: invoked by ghp4
//postcondition: returns the movie MPAA rating
public String getRating()
{
return rating;
}
//setID
//precondition: invoked by ghp4
//postcondition: returns the movie ID number
public int getID()
{
return id;
}
}
Contact List:
ghp5.java
/*
File: ghp5.java
By: Ronny L. Bull
Date: 6-10-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 14 pg 787 problem 2
Descripton: Driver program for contact database
Precondition: Creates instances of the class Contact & ContactList
Postconditon:
Provides a main menu to choose options from
Allows a user to add a contact
Allows a user to search for a contact
Allows a user to delete a contact
Displays contact information
Displays all contacts
*/
/*
Dictonary of Variables:
myFirstName; String, contacts first name
myLastName; String, contacts last name
myPhone; String, contacts phone number
myEmail; String, contacts email address
mySearch; String, user's search string
choice; int, menu option
del; String, deletion confirmation
*/
import java.util.Scanner; //Import Scanner utility
//Main
public class ghp5
{
public static void main(String[] args)
{
//Setup keyboard input scanner
Scanner keyboard = new Scanner(System.in);
//Variables
String myFirstName;
String myLastName;
String myPhone;
String myEmail;
String mySearch;
int choice = 0;
String del;
//Create an object called list of class ContactList
ContactList list = new ContactList();
//Welcome the user
System.out.println("*** Contact Database ***");
System.out.println("");
//Loop until exit (4) is chosen
while(choice != 4)
{
//Main Menu
System.out.println("** Main Menu **");
System.out.println("What would you like to do?");
System.out.println("1. Add a new contact");
System.out.println("2. Search for a contact");
System.out.println("3. Display all contacts");
System.out.println("4. Exit");
//Prompt user for menu choice
System.out.println("Please enter the number of your choice: ");
choice = keyboard.nextInt();
//Process choice
if(choice == 1)
{
// Create an object called contact of class Contact
Contact contact = new Contact();
//Prompt for new contact's first name
System.out.println("Please enter the contact's first name");
myFirstName = keyboard.next();
contact.setFirstName(myFirstName);
//Prompt for new contact's last name
System.out.println("Please enter the contact's last name");
myLastName = keyboard.next();
contact.setLastName(myLastName);
//Prompt for new contact's phone number
System.out.println("Please enter the contact's phone number");
myPhone = keyboard.next();
contact.setPhone(myPhone);
//Prompt for new contact's email address
System.out.println("Please enter the contact's email address");
myEmail = keyboard.next();
contact.setEmail(myEmail);
//Output results
list.addContact(contact);
System.out.println("The new contact has been entered as: ");
System.out.println("Name: " + contact.getFirstName() + " " + contact.getLastName() );
System.out.println("Phone: " + contact.getPhone());
System.out.println("Email: " + contact.getEmail());
System.out.println("");
}
else if(choice == 2)
{
//Search for a contact
System.out.println("Please enter your search string");
mySearch = keyboard.next();
list.searchArray(mySearch);
System.out.println("");
//Prompt for deletion
System.out.println("Would you like to delete this contact? (y/n)");
del = keyboard.next();
if(del.equalsIgnoreCase("y"))
{
list.delete(mySearch);
}
}
else if(choice == 3)
{
//Display all contacts
list.getAll();
System.out.println("");
}
}
}
}
Contact.java
/*
File: Contact.java
By: Ronny L. Bull
Date: 6-10-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 14 pg 787 problem 2
Descripton: Class used to create and display a contact database.
Precondition: Creates an instance of the class Contact
Postconditon:
Sets new contact's first name
Sets new contact's last name
Sets new contact's phone number
Sets new contact's email address
*/
/*
Dictonary of Variables:
firstName; String, contacts first name
lastName; String, contacts last name
phone; String, contacts phone number
email; String, contacts email address
*/
//Define the class
public class Contact
{
//Instance Variables
private String firstName;
private String lastName;
private String phone;
private String email;
//Mutator Methods
//setFirstName
//precondition: invoked by ghp5
//postcondition: sets the contact's first name
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
//setLastName
//precondition: invoked by ghp5
//postcondition: sets contact's last name
public void setLastName(String lastName)
{
this.lastName = lastName;
}
//setPhone
//precondition: invoked by ghp5
//postcondition: sets the contact's phone number
public void setPhone(String phone)
{
this.phone = phone;
}
//setEmail
//precondition: invoked by ghp5
//postcondition: sets the contact's email address
public void setEmail(String email)
{
this.email = email;
}
//Accessor Method
//getFirstName
//precondition: invoked by ghp5
//postcondition: returns contact's first name
public String getFirstName()
{
return firstName;
}
//getLastName
//precondition: invoked by ghp5
//postcondition: returns contact's last name
public String getLastName()
{
return lastName;
}
//getPhone
//precondition: invoked by ghp5
//postcondition: returns contact's phone number
public String getPhone()
{
return phone;
}
//getEmail
//precondition: invoked by ghp5
//postcondition: returns contact's email address
public String getEmail()
{
return email;
}
//toString
//precondition: none
//postcondition: returns the object as a string for use in ContactList
public String toString()
{
return "First name: " + firstName + "\n" +
"Last name: " + lastName + "\n" +
"Phone: " + phone + "\n" +
"Email: " + email;
}
}
ContactList.java
/*
File: ContactList.java
By: Ronny L. Bull
Date: 6-10-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 14 pg 787 problem 2
Descripton: Class used to search and display a contact database.
Precondition: Creates an instance of the class ContactList
Postconditon:
Adds a new contact to the database
Searches contact database
Displays contact information
Displays all contacts
Deletes a contact
*/
/*
Dictonary of Variables:
index; int, arrayList index counter
*/
import java.util.ArrayList; //Import Array List
//Define the class
public class ContactList
{
//Create Array List
ArrayList<Contact> contactDB = new ArrayList<Contact>();
//Instance Variables
//Mutator Methods
//addList
//precondition: invoked by ghp5
//postcondition: adds the contact information to the arraylist
public void addContact(Contact newContact)
{
contactDB.add(newContact);
}
//delete
//precondition: invoked by ghp5
//postcondition: deletes a contact
//Foreach code adapted from: Savitch Absolute Java - pg. 759
//Adapted by: Ronny L. Bull
//Date: 6-13-2010
public void delete(String search)
{
System.out.println("deleting contact...");
int index = 0;
for (Contact element : contactDB)
{
if(element.getFirstName().equalsIgnoreCase(search))
{
contactDB.remove(index);
System.out.println("Contact removed");
}
else if(element.getLastName().equalsIgnoreCase(search))
{
contactDB.remove(index);
System.out.println("Contact removed");
}
else if(element.getPhone().equalsIgnoreCase(search))
{
contactDB.remove(index);
System.out.println("Contact removed");
}
else if(element.getEmail().equalsIgnoreCase(search))
{
contactDB.remove(index);
System.out.println("Contact removed");
}
index++;
}
}
//Accessor Method
//searchArray
//precondition: invoked by ghp5
//postcondition: searches the arraylist for a contact
//Foreach code adapted from: Savitch Absolute Java - pg. 759
//Adapted by: Ronny L. Bull
//Date: 6-13-2010
public void searchArray(String search)
{
System.out.println("Searching for " + search + " ...");
for (Contact element : contactDB)
{
if(element.getFirstName().equalsIgnoreCase(search))
{
System.out.println(element);
System.out.println("");
}
else if(element.getLastName().equalsIgnoreCase(search))
{
System.out.println(element);
System.out.println("");
}
else if(element.getPhone().equalsIgnoreCase(search))
{
System.out.println(element);
System.out.println("");
}
else if(element.getEmail().equalsIgnoreCase(search))
{
System.out.println(element);
System.out.println("");
}
}
}
//getAll
//precondition: invoked by ghp5
//postcondition: returns all contacts in the database
//Foreach code adapted from: Savitch Absolute Java - pg. 759
//Adapted by: Ronny L. Bull
//Date: 6-13-2010
public void getAll()
{
System.out.println("Displaing all contacts ...");
for (Contact element : contactDB)
{
System.out.println(element);
System.out.println("");
}
}
}
Decimal to Binary Converter (SWING):
ghp6.java
/*
File: ghp6.java
By: Ronny L. Bull
Date: 6-28-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 17 pg 1010 problem 4
Descripton: This program provides decimal to binary number conversion
Precondition: User runs program and inputs a decimal number
Postconditon:
GUI is provided for user interaction
Clear button to clear text fields
Convert button to process the input
Exit button to exit program
Converts decimal number to binary number
*/
/*
Dictonary of Variables:
WIDTH, int; Window Width
HEIGHT, int; Window Height
NUM, int; Text field length
decIn, JTextField; Text input for decimal numbers
binOut, JTextField; Text output for binary numbers
myDec, int; Integer version of user input
myBin, String; binary string
*/
/*
Code Adaptation Note: All SWING and AWT code was adapted from Savitch "Absolute Java" chapter 17
Adapted By: Ronny L. Bull
Date: 6-28-2010
*/
//Imports
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import javax.swing.JTextField;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class ghp6 extends JFrame implements ActionListener
{
//Variables
public static final int WIDTH = 480;
public static final int HEIGHT = 320;
public static final int NUM = 15;
private JTextField decIn;
private JTextField binOut;
//Main
public static void main(String[] args)
{
//Create the gui object from the ghp6 class
ghp6 gui = new ghp6();
//Set the gui to visible
gui.setVisible(true);
}
//GUI
public ghp6()
{
//Setup Window
//Window Title
super("Decimal to Binary Conversion");
//Window Size
setSize(WIDTH, HEIGHT);
//Close Button Event
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Layout Setup
setLayout(new BorderLayout());
//Setup Input Panel
JPanel inputPanel = new JPanel();
//Decimal Label
JLabel dlabel = new JLabel("Your Decimal Number: ");
inputPanel.add(dlabel);
//Decimal Text Field
decIn = new JTextField(NUM);
inputPanel.add(decIn);
//Add Input Panel to the layout
add(inputPanel, BorderLayout.NORTH);
//Setup Output Panel
JPanel outputPanel = new JPanel();
//Binary Label
JLabel blabel = new JLabel("It's Binary Equivalent: ");
outputPanel.add(blabel);
//Binary Text Field
binOut = new JTextField(NUM);
outputPanel.add(binOut);
//Add Output Panel to the layout
add(outputPanel, BorderLayout.CENTER);
//Setup Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
//Process Button
JButton calcButton = new JButton("Convert");
calcButton.addActionListener(this);
buttonPanel.add(calcButton);
//Clear Button
JButton clearButton = new JButton("Clear");
clearButton.addActionListener(this);
buttonPanel.add(clearButton);
//Setup Exit Button
JButton exitButton = new JButton("Exit");
exitButton.addActionListener(this);
buttonPanel.add(exitButton);
//Add Button Panel to the layout
add(buttonPanel, BorderLayout.SOUTH);
}
//Action Listener
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
if (actionCommand.equals("Exit"))
{
//Exit Program
System.exit(0);
}
else if (actionCommand.equals("Clear"))
{
//Clear both text fields
decIn.setText("");
binOut.setText("");
}
else if (actionCommand.equals("Convert"))
{
//Create convert object from Class Convert
Convert convert = new Convert();
//Convert user input string to an integer
int myDec = Integer.parseInt(decIn.getText());
//Send the decimal number stored in myDec to the setToBinary method in Convert
//and store the resulting string in myBin
String myBin = convert.toBinary(myDec);
//Output the contents of myBin to the binOut text field
binOut.setText(myBin);
}
}
}
Convert.java
/*
File: Convert.java
By: Ronny L. Bull
Date: 6-28-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 17 pg 1010 problem 4
Descripton: Class used to convert decimal to binary
Precondition: Invoked by ghp6
Postconditon:
Converts a decimal number to it's binary equivalent
*/
/*
Dictonary of Variables:
dec; int, user input decimal number
bin; String, binary equivalant
*/
//Main
public class Convert
{
//Variables
private int dec;
private String bin;
//toBinary
//precondition: invoked by ghp6
//postondition: converts decimal to binary
public String toBinary(int dec)
{
this.bin = Integer.toBinaryString(dec);
return this.bin;
}
}
Tic-Tac-Toe Game (SWING):
/*
File: ghp7.java
By: Ronny L. Bull
Date: 7-18-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
IDE: Eclipse 3.4.0
Problem: Savitch "Absolute Java" Ch 17 pg 1010 problem 2
Descripton: Tic-Tac-Toe Game
Precondition: User runs program
Postconditon:
GUI is provided for user interaction
Game board is made up of 9 buttons
Displays messages (ie, player, and winner)
Buttons change to X or O depending on player
Determines who won or if the game is a tie
Reset game via reset menu item
Exit game via exit menu item
*/
/*
Dictionary of Variables:
WIDTH, int; Window Width
HEIGHT, int; Window Height
message, JLabel; displays messages
button(0-8), JButton; game board buttons
win, boolean; game won?
player, int; player number
counter, int; game counter
mark, String; players mark [X or O]
*/
/*
Code Adaptation Note: All SWING and AWT code was adapted from Savitch "Absolute Java" chapter 17
Adapted By: Ronny L. Bull
Date: 7-18-2010
*/
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
public class ghp7 extends JFrame implements ActionListener
{
//Variables
private static final long serialVersionUID = 1L; //Something eclipse made me toss in
public static final int WIDTH = 300;
public static final int HEIGHT = 300;
final JLabel message = new JLabel();
private String mark = "X";
private boolean win = false;
private int player = 1;
private int counter = 0;
private JButton button0 = new JButton();
private JButton button1 = new JButton();
private JButton button2 = new JButton();
private JButton button3 = new JButton();
private JButton button4 = new JButton();
private JButton button5 = new JButton();
private JButton button6 = new JButton();
private JButton button7 = new JButton();
private JButton button8 = new JButton();
//Main
public static void main(String[] args)
{
//Create the GUI object from the ghp7 class
ghp7 gui = new ghp7();
//Set the GUI to visible
gui.setVisible(true);
}
//GUI
public ghp7()
{
//Setup Window
//Window Title
super("Tic-Tac-Toe");
//Window Size
setSize(WIDTH, HEIGHT);
//Close Button Event
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Layout Setup
setLayout(new BorderLayout());
//Setup Menu Bar
JMenu mainMenu = new JMenu("Menu");
JMenuItem reset = new JMenuItem("Reset");
reset.addActionListener(this);
mainMenu.add(reset);
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(this);
mainMenu.add(exit);
JMenuBar bar = new JMenuBar();
bar.add(mainMenu);
setJMenuBar(bar);
//Setup Player Panel
JPanel playerPanel = new JPanel();
//Player Label
message.setText("Welcome to Tic-Tac-Toe!");
playerPanel.add(message);
//Add Player Panel to the layout
add(playerPanel, BorderLayout.NORTH);
//Setup Game Panel
JPanel gamePanel = new JPanel();
//Game board grid
GridLayout gameBoard = new GridLayout(3,3);
gamePanel.setLayout(gameBoard);
//Display the game buttons
gamePanel.add(button0);
button0.addActionListener(this);
gamePanel.add(button1);
button1.addActionListener(this);
gamePanel.add(button2);
button2.addActionListener(this);
gamePanel.add(button3);
button3.addActionListener(this);
gamePanel.add(button4);
button4.addActionListener(this);
gamePanel.add(button5);
button5.addActionListener(this);
gamePanel.add(button6);
button6.addActionListener(this);
gamePanel.add(button7);
button7.addActionListener(this);
gamePanel.add(button8);
button8.addActionListener(this);
//Add Game Panel to the layout
add(gamePanel, BorderLayout.CENTER);
}
//Action Listener
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
//Increase the game counter
counter++;
//Exit Game
if (actionCommand.equals("Exit"))
{
//Exit Program
System.exit(0);
}
else if (actionCommand.equals("Reset"))
{
//Reset Game
//Clear the board
button0.setText("");
button1.setText("");
button2.setText("");
button3.setText("");
button4.setText("");
button5.setText("");
button6.setText("");
button7.setText("");
button8.setText("");
//Enable the buttons
button0.setEnabled(true);
button1.setEnabled(true);
button2.setEnabled(true);
button3.setEnabled(true);
button4.setEnabled(true);
button5.setEnabled(true);
button6.setEnabled(true);
button7.setEnabled(true);
button8.setEnabled(true);
//Reset variables to defaults
message.setText("Welcome to Tic-Tac-Toe!");
player = 1;
counter = 0;
mark = "X";
win = false;
}
//Detect if a button was pressed
//If so mark it and disable it
JButton clicked = (JButton)e.getSource();
clicked.setText(mark);
clicked.setEnabled(false);
//Set next player
if (player == 1)
{
player = 2;
mark = "O";
message.setText(mark + "'s turn!");
}
else if (player == 2)
{
player = 1;
mark = "X";
message.setText(mark + "'s turn!");
}
//Find winner
//First Horizontal Row
if (button0.getText().equals(button1.getText()) && button1.getText().equals(button2.getText()) && button0.getText().equals("")==false)
win=true;
//Second Horizontal Row
if (button3.getText().equals(button4.getText()) && button4.getText().equals(button5.getText()) && button3.getText().equals("")==false)
win=true;
//Third Horizontal Row
if (button6.getText().equals(button7.getText()) && button7.getText().equals(button8.getText()) && button6.getText().equals("")==false)
win=true;
//First Vertical Row
if (button0.getText().equals(button3.getText()) && button3.getText().equals(button6.getText()) && button0.getText().equals("")==false)
win=true;
//Second Vertical Row
if (button1.getText().equals(button4.getText()) && button4.getText().equals(button7.getText()) && button1.getText().equals("")==false)
win=true;
//Third Vertical Row
if (button2.getText().equals(button5.getText()) && button5.getText().equals(button8.getText()) && button2.getText().equals("")==false)
win=true;
//First Cross Row
if (button0.getText().equals(button4.getText()) && button4.getText().equals(button8.getText()) && button0.getText().equals("")==false)
win=true;
//Second Cross Row
if (button2.getText().equals(button4.getText()) && button4.getText().equals(button6.getText()) && button2.getText().equals("")==false)
win=true;
//Process win or tie
if(win == true)
{
//Set the mark to the correct winner
if (mark.equals("X"))
mark = "0";
else
mark = "X";
//Display the winner in the message area
message.setText("Game Over: " + mark + " Wins!");
//Disable all buttons
button0.setEnabled(false);
button1.setEnabled(false);
button2.setEnabled(false);
button3.setEnabled(false);
button4.setEnabled(false);
button5.setEnabled(false);
button6.setEnabled(false);
button7.setEnabled(false);
button8.setEnabled(false);
}
else if(counter == 9 && win == false)
{
//Display the tie message
message.setText("Game Over: Tie!");
}
}
}
Change Font Style, Size, & Color (SWING):
/*
File: ghp8.java
By: Ronny L. Bull
Date: 7-18-2010
Development OS: Gentoo Linux
Java Version: sun-jdk-1.6.0.20
Problem: Savitch "Absolute Java" Ch 18 pg 1074 problem 6
Descripton: Font Chooser
Precondition: User runs program, and inputs text
Postconditon:
GUI is provided for user interaction
User can select Font, Size, and style (ittalic/bold)
Display button is used to display font changes
Exit via exit menu item
*/
/*
Dictonary of Variables:
WIDTH, int; Window Width
HEIGHT, int; Window Height
NUM, int; Text Field Length
inputText, JTextField; text field input
fontObject, Font; current font settings
text, String; user input
fontStyle, int; Font style (plain = 0, bold = 1, italic = 2, both =3)
fontName, String; font family name
fontSize, int; font point size
*/
/*
Code Adaptation Note: All SWING and AWT code was adapted from Savitch "Absolute Java" chapters 17 & 18
Adapted By: Ronny L. Bull
Date: 7-18-2010
*/
//Imports
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JMenuBar;
import java.awt.Font;
import java.awt.Graphics;
public class ghp8 extends JFrame implements ActionListener
{
//Variables
public static final int WIDTH = 480;
public static final int HEIGHT = 320;
public static final int NUM = 20;
private JTextField inputText;
private String text = "";
private String fontName = "Sans";
private int fontStyle = 0;
private int fontSize = 9;
private Font fontObject = new Font(fontName, fontStyle, fontSize);
//Main
public static void main(String[] args)
{
//Create the gui object from the ghp8 class
ghp8 gui = new ghp8();
//Set the gui to visible
gui.setVisible(true);
}
//GUI
public ghp8()
{
//Setup Window
//Window Title
super("Font Sampler");
//Window Size
setSize(WIDTH, HEIGHT);
//Close Button Event
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
//Layout Setup
setLayout(new BorderLayout());
//Setup Menu Bar
JMenuBar bar = new JMenuBar();
setJMenuBar(bar);
//Setup the main menu
JMenu mainMenu = new JMenu("Menu");
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(this);
mainMenu.add(exit);
bar.add(mainMenu);
//Setup the font menu
JMenu fontMenu = new JMenu("Fonts");
JMenuItem font1 = new JMenuItem("Monospaced");
font1.addActionListener(this);
fontMenu.add(font1);
JMenuItem font2 = new JMenuItem("SansSerif");
font2.addActionListener(this);
fontMenu.add(font2);
JMenuItem font3 = new JMenuItem("Serif");
font3.addActionListener(this);
fontMenu.add(font3);
JMenuItem font4 = new JMenuItem("Times New Roman");
font4.addActionListener(this);
fontMenu.add(font4);
JMenuItem font5 = new JMenuItem("Courier New");
font5.addActionListener(this);
fontMenu.add(font5);
bar.add(fontMenu);
//Setup the size menu
JMenu sizeMenu = new JMenu("Size");
JMenuItem size1 = new JMenuItem("9");
size1.addActionListener(this);
sizeMenu.add(size1);
JMenuItem size2 = new JMenuItem("10");
size2.addActionListener(this);
sizeMenu.add(size2);
JMenuItem size3 = new JMenuItem("12");
size3.addActionListener(this);
sizeMenu.add(size3);
JMenuItem size4 = new JMenuItem("14");
size4.addActionListener(this);
sizeMenu.add(size4);
JMenuItem size5 = new JMenuItem("16");
size5.addActionListener(this);
sizeMenu.add(size5);
JMenuItem size6 = new JMenuItem("24");
size6.addActionListener(this);
sizeMenu.add(size6);
JMenuItem size7 = new JMenuItem("32");
size7.addActionListener(this);
sizeMenu.add(size7);
bar.add(sizeMenu);
//Setup the style menu
JMenu styleMenu = new JMenu("Style");
JMenuItem plain = new JMenuItem("Plain");
plain.addActionListener(this);
styleMenu.add(plain);
JMenuItem bold = new JMenuItem("Bold");
bold.addActionListener(this);
styleMenu.add(bold);
JMenuItem italic = new JMenuItem("Italic");
italic.addActionListener(this);
styleMenu.add(italic);
JMenuItem both = new JMenuItem("Both");
both.addActionListener(this);
styleMenu.add(both);
bar.add(styleMenu);
//Setup Input Panel
JPanel inputPanel = new JPanel();
//Input Text Label
JLabel inLabel = new JLabel("Your text: ");
inputPanel.add(inLabel);
//Input Text Field
inputText = new JTextField(NUM);
inputPanel.add(inputText);
//Add Input Panel to the layout
add(inputPanel, BorderLayout.NORTH);
//Setup Button Panel
JPanel buttonPanel = new JPanel();
buttonPanel.setLayout(new FlowLayout());
//Display Button
JButton displayButton = new JButton("Display");
displayButton.addActionListener(this);
buttonPanel.add(displayButton);
//Add Button Panel to the layout
add(buttonPanel, BorderLayout.SOUTH);
}
public void paint(Graphics g)
{
super.paint(g);
g.setFont(fontObject);
g.drawString(text, 20,150);
}
//Action Listener
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
//Handle Exit
if (actionCommand.equals("Exit"))
{
//Exit Program
System.exit(0);
}
//Handle Font Options
if (actionCommand.equals("Monospaced"))
fontName = "Monospaced";
if (actionCommand.equals("SansSerif"))
fontName = "SansSerif";
if (actionCommand.equals("Serif"))
fontName = "Serif";
if (actionCommand.equals("Times New Roman"))
fontName = "Times New Roman";
if (actionCommand.equals("Courier New"))
fontName = "Courier New";
if (actionCommand.equals("Plain"))
fontStyle = 0;
if (actionCommand.equals("Bold"))
fontStyle = 1;
if (actionCommand.equals("Italic"))
fontStyle = 2;
if (actionCommand.equals("Both"))
fontStyle = 3;
if (actionCommand.equals("9"))
fontSize = 9;
if (actionCommand.equals("10"))
fontSize = 10;
if (actionCommand.equals("12"))
fontSize = 12;
if (actionCommand.equals("14"))
fontSize = 14;
if (actionCommand.equals("16"))
fontSize = 16;
if (actionCommand.equals("24"))
fontSize = 24;
if (actionCommand.equals("32"))
fontSize = 32;
//Handle Display Event
if (actionCommand.equals("Display"))
{
//Output to text field
fontObject = new Font(fontName, fontStyle, fontSize);
text = inputText.getText();
repaint();
}
}
}
