Contents
- ./cards/Card.java
- ./cards/Deck.java
- ./employee/Employee.java
- ./employee/EmployeeNameComparator.java
- ./examples/BigramFixed.java
- ./examples/Bigram.java
- ./examples/Dice.java
- ./examples/Fruit.java
- ./examples/OverloadPlay.java
- ./examples/OverridePlay.java
- ./examples/PlanetTest.java
./cards/Card.java 1/11
[top][prev][next]
package cards;
/**
* Represents a playing card. Demonstrates use of enumerated types, enum.
*/
public class Card {
/**
* Represents the ranks in a deck of playing cards
*/
public enum Rank {
DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING, ACE;
}
/**
* Represents the suits in a deck of playing cards
*/
public enum Suit {
CLUBS, DIAMONDS, HEARTS, SPADES;
}
// a card won't change its rank or suit after it is created
private final Rank rank;
private final Suit suit;
/**
* Creates a new card object, with the given rank and suit
*
* @param rank
* @param suit
*/
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
/**
* Returns this card's rank
*
* @return card's rank
*/
public Rank rank() {
return rank;
}
/**
* Returns this card's suit
*
* @return card's suit
*/
public Suit suit() {
return suit;
}
/**
* 10, J, Q, K: 10 points A: 15 points all others: 5 points
*
* @return the value of the card in the game of Rummy
*/
public int getRummyValue() {
switch( rank ) {
case ACE:
return 15;
case TEN:
case JACK:
case QUEEN:
case KING:
return 10;
default:
return 5;
}
}
/**
* Determines if this card and another card have the same suit. Returns true
* if they do.
*
* @param c
* another Card to compare
* @return true iff the cards have the same suit
*/
public boolean sameSuit(Card c) {
return this.suit.equals(c.suit);
// return this.suit == c.suit;
// return this.suit().equals(c.suit());
}
/**
* Returns a string representation of this card.
*
* @return string representation of a Card in the form <rank> of
* <suit>
*/
@Override
public String toString() {
// leverages toString() methods of Rank and Suit
return rank + " of " + suit;
}
public static void main(String args[]) {
Card jackOfDiamonds = new Card(Rank.JACK, Suit.DIAMONDS);
Card aceOfDiamonds = new Card(Rank.ACE, Suit.DIAMONDS);
System.out.println(jackOfDiamonds);
if (jackOfDiamonds.sameSuit(aceOfDiamonds)) {
System.out.println(jackOfDiamonds + " and " + aceOfDiamonds
+ " are the same suit.");
}
System.out.println("The rummyValue of " + jackOfDiamonds + " is "
+ jackOfDiamonds.getRummyValue());
}
}
./cards/Deck.java 2/11
[top][prev][next]
package cards;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Represents a deck of playing cards
*
* @author Sara Sprenkle and CS209
*
*/
public class Deck {
// define our variable as an interface variable, List.
// Note that only Card objects can be put into the list or taken out of the
// list.
/** a list of Card objects */
private List<Card> deck = new ArrayList<Card>(); // Assign the ArrayList
// implementation
// to the List variable
/**
* Creates a new, shuffled deck of cards
*/
public Deck() {
restart(true);
}
/**
* Creates a new deck of cards
*
* @param shuffle
* - true if the cards should be shuffled
*/
public Deck(boolean shuffle) {
restart(shuffle);
}
/**
* Restart the deck from the beginning.
*
* @param shuffle
* - true if the cards should be shuffled
*/
public void restart(boolean shuffle) {
// removes all the Cards from the deck
deck.clear();
// Use the enums defined in the Card class
for (Card.Suit suit : Card.Suit.values()) {
for (Card.Rank rank : Card.Rank.values()) {
Card c = new Card(rank, suit);
deck.add(c);
}
}
if (shuffle) {
shuffle();
}
}
/**
* Display the contents of the deck.
*/
public void display() {
for (Card c : deck) {
System.out.println(c);
}
}
/**
* Shuffles the deck of cards
*/
public void shuffle() {
Collections.shuffle(deck);
}
/**
* Draws the first card from the deck, removes it from the deck, and returns
* the chosen card
*
* @return the top card from the deck, which is removed
*/
public Card draw() {
return deck.remove(0);
}
/**
* Returns a list of cards that are drawn (thus from the deck.
*
* @param numCards
* @return a list of cards (of the specified size)
*/
public List<Card> deal(int numCards) {
List<Card> hand = new ArrayList<Card>();
for (int i = 0; i < numCards; i++) {
hand.add(draw());
}
return hand;
}
/**
* @param args
*/
public static void main(String[] args) {
Deck d = new Deck();
d.display();
}
}
./employee/Employee.java 3/11
[top][prev][next]
package employee;
import java.util.Arrays;
/**
* Represents an employee with an id, name, and age
*
* @author sprenkle
*
*/
public class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
/**
* Creates an employee with the given id, name, and age
*
* @param id
* the employee's given unique id
* @param name
* the employee's full name
* @param age
* the employee's age in whole years
*/
public Employee(int id, String name, int age) {
super();
this.id = id;
this.name = name;
this.age = age;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder rep = new StringBuilder(getName());
rep.append("\n\t Employee ID: " + this.getId());
rep.append("\n\t Age:" + this.getAge());
return rep.toString();
}
/**
* Returns the employee's id
*
* @return the id
*/
public int getId() {
return id;
}
/**
* Sets the employee's id
*
* @param id
* the id to set
*/
public void setEmpId(int empId) {
this.id = empId;
}
/**
* @return the employee's name
*/
public String getName() {
return name;
}
/**
* @param name
* -- the name of the employee
*/
public void setName(String name) {
this.name = name;
}
/**
* @return the age
*/
public int getAge() {
return age;
}
/**
* @param age
* -- the age of the employee
*/
public void setAge(int age) {
this.age = age;
}
/**
* Compares employees by their ids
*/
@Override
public int compareTo(Employee o) {
// note how this simple statement does what we want
return this.id - o.id;
}
public static void main(String[] args) {
Employee a = new Employee(12, "Homer J. Simpson", 38);
Employee b = new Employee(1, "Charles Montgomery Burns", 104);
Employee c = new Employee(3, "Waylon Smithers", 43);
Employee d = new Employee(14, "Carl Carlson", 38);
Employee e = new Employee(15, "Lenny Leonard", 38);
System.out.println("Comparing " + a.getName() + " with " + b.getName()
+ ": " + a.compareTo(b));
System.out.println("\nSorted: ");
Employee[] employees = { a, b, c, d, e };
Arrays.sort(employees);
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
./employee/EmployeeNameComparator.java 4/11
[top][prev][next]
package employee;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* @author sprenkle
*
*/
public class EmployeeNameComparator implements Comparator<Employee> {
/**
* Compare Employees by their names
*/
@Override
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
/**
* @param args
*/
public static void main(String[] args) {
Employee a = new Employee(12, "Homer J. Simpson", 38);
Employee b = new Employee(1, "Charles Montgomery Burns", 104);
Employee c = new Employee(3, "Waylon Smithers", 43);
Employee d = new Employee(14, "Carl Carlson", 38);
Employee e = new Employee(15, "Lenny Leonard", 38);
System.out.println("Comparing " + a.getName() + " with " + b.getName()
+ ": " + a.compareTo(b));
List<Employee> employees = new ArrayList<Employee>();
employees.add(a);
employees.add(b);
employees.add(c);
employees.add(d);
employees.add(e);
System.out.println("\nSorted natural order: ");
Collections.sort(employees);
for (Employee emp : employees) {
System.out.println(emp);
}
System.out.println("\nSorted by name: ");
Collections.sort(employees, new EmployeeNameComparator());
for (Employee emp : employees) {
System.out.println(emp);
}
}
}
./examples/BigramFixed.java 5/11
[top][prev][next]
package examples;
import java.util.Set;
import java.util.HashSet;
/**
* From <em>Effective Java</em> "Can you spot the bug?"
*
* Fixed example of Bigram.java
*
* @author Joshua Bloch
*/
public class BigramFixed {
private final char first;
private final char second;
public BigramFixed(char first, char second) {
this.first = first;
this.second = second;
}
@Override
public boolean equals(Object o) {
if (! (o instanceof BigramFixed))
return false;
BigramFixed b = (BigramFixed) o;
return b.first == first && b.second == second;
}
public int hashCode() {
return 31 * first + second;
}
public static void main(String[] args) {
Set<BigramFixed> s = new HashSet<BigramFixed>();
for (int i = 0; i < 10; i++)
for (char ch = 'a'; ch <= 'z'; ch++)
s.add(new BigramFixed(ch, ch));
System.out.println(s.size());
}
}
./examples/Bigram.java 6/11
[top][prev][next]
package examples;
import java.util.Set;
import java.util.HashSet;
/**
* From <em>Effective Java</em>
* "Can you spot the bug?"
* @author Joshua Bloch
*/
public class Bigram {
private final char first;
private final char second;
public Bigram(char first, char second) {
this.first = first;
this.second = second;
}
public boolean equals(Bigram b) {
return b.first == first && b.second == second;
}
public int hashCode() {
return 31 * first + second;
}
public static void main(String[] args) {
Set<Bigram> s = new HashSet<Bigram>();
for (int i = 0; i < 10; i++)
for (char ch = 'a'; ch <= 'z'; ch++)
s.add(new Bigram(ch, ch));
System.out.println(s.size());
}
}
./examples/Dice.java 7/11
[top][prev][next]
package examples;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* Example of a common programmer bug when using an iterator.
*
*/
public class Dice {
enum Face {
ONE, TWO, THREE, FOUR, FIVE, SIX
};
/**
* @param args
*/
public static void main(String[] args) {
System.out.println("Goal: Show all combinations from rolling two dice");
// This loop doesn't produce the expected results
Collection<Face> faces = Arrays.asList(Face.values());
System.out.println("Unexpected results: ");
for (Iterator<Face> i = faces.iterator(); i.hasNext();) {
for (Iterator<Face> j = faces.iterator(); j.hasNext();) {
System.out.println(i.next() + " " + j.next());
}
}
System.out.println("Expected results: ");
// This loop does.
for (Face one : Face.values()) {
for (Face two : Face.values()) {
System.out.println(one + " " + two);
}
}
}
}
./examples/Fruit.java 8/11
[top][prev][next]
package examples;
/**
* Example of using Enums.
*
* @author sprenkle
*
*/
public class Fruit {
public enum Apple {
FUJI, EMPIRE, GRANNY_SMITH
};
public enum Orange {
NAVEL, TEMPLE, BLOOD
};
/**
* @param args
*/
public static void main(String[] args) {
for (Apple a : Apple.values()) {
System.out.println(a);
}
}
}
./examples/OverloadPlay.java 9/11
[top][prev][next]
package examples;
/**
* What is the output from the main method of OverloadPlay ?
*
* @author sprenkle
*
*/
class Parent {
public void method() {
System.out.println("Parent");
}
}
class Child extends Parent {
@Override
public void method() {
System.out.println("Child");
}
}
public class OverloadPlay {
public static void print(Parent parent) {
System.out.println("Static Parent");
}
public static void print(Child child) {
System.out.println("Static Child");
}
public void instancePrint(Parent parent) {
System.out.println("Parent");
}
public void instancePrint(Child child) {
System.out.println("Child");
}
public static void main(String[] args) {
Child child = new Child();
Parent p = child;
print(p);
new OverloadPlay().instancePrint(p);
}
}
./examples/OverridePlay.java 10/11
[top][prev][next]
package examples;
/**
* Another example of dynamic dispatch. Note that Parent and Child are defined
* in OverloadPlay
*
* @author sprenkle
*
*/
public class OverridePlay {
public static void main(String[] args) {
Child child = new Child();
Parent p = child;
p.method();
}
}
./examples/PlanetTest.java 11/11
[top][prev][next]
package examples;
/**
* Example demonstrates a more sophisticated enumerated type.
*
*/
public class PlanetTest {
public enum Planet {
MERCURY(3.302e+23, 2.439e6), VENUS(4.869e+24, 6.0518e6), EARTH(
5.976e+24, 6.37814e6), MARS(6.421e+23, 3.3972e6), JUPITER(
1.9e+27, 7.1492e7), SATURN(5.688e+26, 6.0268e7), URANUS(
8.686e+25, 2.5559e7), NEPTUNE(1.024e+26, 2.4746e7);
private final double mass;
private final double radius;
private final double surfaceGravity;
private static final double G = 6.67300E-11;
// Note: Package-private; Can't be more visible than package-private
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
surfaceGravity = G * mass / (radius * radius);
}
public double mass() {
return mass;
}
public double radius() {
return radius;
}
public double surfaceGravity() {
return surfaceGravity;
}
public double surfaceWeight(double mass) {
return mass * surfaceGravity; // F = ma
}
}
/**
* @param args
*/
public static void main(String[] args) {
double earthWeight = 150;
double mass = earthWeight / Planet.EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %10.4f%n", p,
p.surfaceWeight(mass));
}
}
Generated by GNU enscript 1.6.4.