Contents
- ./cards/Card.java
- ./cards/Deal.java
- ./cards/Deck.java
- ./comparisons/LinkedListForEach.java
- ./comparisons/LinkedListGet.java
- ./comparisons/LinkedListIterator.java
- ./examples/FindDuplicates.java
- ./examples/Fruit.java
- ./examples/PetSurvey3.java
- ./examples/PlanetTest.java
- ./examples/TestShortcuts.java
./cards/Card.java 1/11
[top][prev][next]
package cards;
/**
* Demonstrates use of "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;
}
private final Rank rank;
private final Suit suit;
public Card(Rank rank, Suit suit) {
this.rank = rank;
this.suit = suit;
}
public Rank rank() {
return rank;
}
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() {
int rummyValue = 0;
switch (rank) {
case ACE:
rummyValue = 15;
break;
case KING:
case QUEEN:
case JACK:
case TEN:
rummyValue = 10;
break;
default:
rummyValue = 5;
}
return rummyValue;
}
/**
*
* @param c
* another Card to compare
* @return true iff the cards have the same suit
*/
public boolean sameSuit(Card c) {
return c.suit.equals(suit);
// return c.suit == suit; // also works because they're enums
}
/**
* leverages toString() methods of Rank and Suit
*/
public String toString() {
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/Deal.java 2/11
[top][prev][next]
package cards;
import java.util.*;
/**
*
*/
class Deal {
/**
* A little different dealing than before... Does not specify the type of
* objects in the List. Doesn't need to--still works.
*
* @param deck
* @param n
* @return
*/
public static List dealHand(List deck, int n) {
int deckSize = deck.size();
List handView = deck.subList(deckSize - n, deckSize);
List hand = new ArrayList(handView);
handView.clear();
return hand;
}
public static void main(String[] args) {
int numHands = Integer.parseInt(args[0]);
int cardsPerHand = Integer.parseInt(args[1]);
// Make a normal 52-card deck.
String[] suit = new String[] { "Spades", "Hearts", "Diamonds", "Clubs" };
String[] rank = new String[] { "Ace", "2", "3", "4", "5", "6", "7",
"8", "9", "10", "Jack", "Queen", "King" };
List<String> deck = new ArrayList<String>();
// initialize the deck
for (int i = 0; i < suit.length; i++)
for (int j = 0; j < rank.length; j++)
deck.add(rank[j] + " of " + suit[i]);
Collections.shuffle(deck);
for (int i = 0; i < numHands; i++)
System.out.println(dealHand(deck, cardsPerHand));
System.out.println("\n Changing decks ... \n");
List<Card> cardDeck = new ArrayList<Card>();
for (Card.Suit s : Card.Suit.values()) {
for (Card.Rank r : Card.Rank.values()) {
cardDeck.add( new Card(r, s) );
}
}
Collections.shuffle(cardDeck);
for (int i = 0; i < numHands; i++)
System.out.println(dealHand(cardDeck, cardsPerHand));
}
}
./cards/Deck.java 3/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;
/**
* Creates a new, shuffled deck of cards
*/
public Deck() {
// Assign the List variable to the ArrayList implementation.
deck = new ArrayList<Card>();
restart(true);
}
/**
* Creates a new deck of cards
* @param isShuffled - true if the cards should be shuffled
*/
public Deck(boolean isShuffled) {
deck = new ArrayList<Card>();
restart(isShuffled);
}
/**
* Restart the deck from the beginning.
* @param isShuffled - true if the cards should be shuffled
*/
public void restart(boolean isShuffled) {
// 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( isShuffled ) {
shuffle();
}
}
/**
* Display the contents of the deck.
*/
public void display() {
// System.out.println(deck);
for (Card c : deck) {
System.out.println(c);
}
}
/**
*
*/
public void shuffle() {
Collections.shuffle(deck);
}
public Card draw() {
return deck.remove(0);
}
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();
}
}
./comparisons/LinkedListForEach.java 4/11
[top][prev][next]
package comparisons;
import java.util.*;
/**
* Code to time for each loop for LinkedList
*
* @author sprenkle
*
*/
public class LinkedListForEach {
/**
* @param args
*/
public static void main(String[] args) {
final int SIZE = 1000000;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < SIZE; i++) {
list.add(7);
}
int count = 0;
for (Integer i : list) {
count += i; // do something
}
System.out.println(count);
}
}
./comparisons/LinkedListGet.java 5/11
[top][prev][next]
package comparisons;
import java.util.*;
/**
* Code to time for loop with get for LinkedList
*
* @author sprenkle
*
*/
public class LinkedListGet {
/**
* @param args
*/
public static void main(String[] args) {
final int SIZE = 1000000;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < SIZE; i++) {
list.add(7);
}
int count = 0;
for (int i = 0; i < SIZE; i++ ) {
count += list.get(i); // do something
}
System.out.println(count);
}
}
./comparisons/LinkedListIterator.java 6/11
[top][prev][next]
package comparisons;
import java.util.*;
/**
* Code to time for each loop for LinkedList
*
* @author sprenkle
*/
public class LinkedListIterator {
/**
* @param args
*/
public static void main(String[] args) {
final int SIZE = 1000000;
List<Integer> list = new LinkedList<Integer>();
for (int i = 0; i < SIZE; i++) {
list.add(7);
}
int count = 0;
for (Iterator<Integer> i = list.iterator(); i.hasNext();) {
Integer value = i.next();
count += value; // do something
}
System.out.println(count);
}
}
./examples/FindDuplicates.java 7/11
[top][prev][next]
package examples;
import java.util.HashSet;
import java.util.Set;
/**
* From the array of command-line arguments, identify the duplicates
*
* @author CS209
*
*/
public class FindDuplicates {
/**
*
* @param args
*/
public static void main(String args[]) {
Set<String> argSet = new HashSet<String>();
for(int i=0; i < args.length; i++ ) {
// try to add argument to set
if( ! argSet.add(args[i]) ) {
System.out.println("Duplicate: " + args[i]);
}
}
System.out.println(argSet.size() + " unique words: " + argSet);
}
}
./examples/Fruit.java 8/11
[top][prev][next]
/**
*
*/
package examples;
/**
* @author sprenkle
*
*/
public class Fruit {
public enum Apple {FUJI, PIPPIN, GRANNY_SMITH};
public enum Orange {NAVEL, TEMPLE, BLOOD};
/**
* @param args
*/
public static void main(String[] args) {
}
}
./examples/PetSurvey3.java 9/11
[top][prev][next]
package examples;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
/**
* This class represents a pet survey, keeping track of the number of votes cast
* for a set of pets. The results are stored in a file.
*
* Modified to use a collection.
*
* @author CS209
*
*/
public class PetSurvey3 {
private String filename;
private int totalVotes = 0;
Map<String, Integer> petToVotes;
public PetSurvey3(String fn) {
this.filename = fn;
petToVotes = new HashMap<String, Integer>();
importResults();
}
/**
* Read the survey data from the file
*/
private void importResults() {
try {
BufferedReader input = new BufferedReader(new FileReader(filename));
String line;
int i = 0;
while ((line = input.readLine()) != null) {
// line format: <animal> <numVotes>
String data[] = line.split(" ");
String animal = data[0];
int numVotes = Integer.parseInt(data[1]);
petToVotes.put(animal, numVotes);
i++;
totalVotes += numVotes;
}
input.close();
} catch (FileNotFoundException e) {
System.out.println(filename
+ ", containing the survey results, not found");
e.printStackTrace();
} catch (IOException e) {
System.out
.println("Something went wrong while importing survey results from"
+ filename);
e.printStackTrace();
}
}
/**
* Store the current voting results into the file
*/
public void storeResults() {
try {
PrintWriter writer = new PrintWriter(filename);
Set<String> keys = petToVotes.keySet();
for (String animal: keys) {
writer.println(animal + " " + petToVotes.get(animal));
}
writer.close();
} catch (IOException e) {
System.out.println("Error storing survey results to file "
+ filename);
e.printStackTrace();
}
}
/**
*
* @return the name of the file containing the survey results
*/
public String getFilename() {
return filename;
}
/**
*
* @return the array of Strings of animal names in the survey
*/
public String[] getAnimals() {
Set<String> animals = petToVotes.keySet();
String[] animalsArray = (String[]) animals.toArray();
return animalsArray;
}
/**
*
* @return the number of votes that have been cast.
*/
public int getTotalVotes() {
return totalVotes;
}
/**
* Casts a vote for the animal
*
* @param animal
*/
public void castVote(String animal) {
Integer numVotes = petToVotes.get(animal);
if( numVotes == null ) {
petToVotes.put(animal, 1);
} else {
petToVotes.put(animal, numVotes+1);
}
totalVotes++;
}
/**
* Display the results from the survey in a nicely formatted way.
*/
public void displayResults() {
System.out.printf("%-10s%7s%13s\n", "Animal", "Votes", "Percentage");
System.out.println("------------------------------");
Set<String> keys = petToVotes.keySet();
for( String animal : keys ) {
int votes = petToVotes.get(animal);
double pct = (double) votes/totalVotes * 100;
System.out.printf("%-10s%7d%12.2f%%\n", animal, votes, pct);
}
System.out.println("Total votes cast: " + totalVotes);
}
/**
* @param args
* not used in this program.
*/
public static void main(String[] args) {
final String mySurveyFile = "petSurvey.dat";
PetSurvey3 survey = new PetSurvey3(mySurveyFile);
System.out.println("Current Results: ");
survey.displayResults();
// Allow User to Vote
Scanner scanner = new Scanner(System.in);
System.out
.print("What animal do you want to vote for as your favorite? (dog, cat, bird, snake, fish, other): ");
String animalVoted = scanner.nextLine();
scanner.close();
survey.castVote(animalVoted);
// Display updated results
System.out.println("Updated Results: ");
survey.displayResults();
survey.storeResults();
}
}
./examples/PlanetTest.java 10/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));
}
}
./examples/TestShortcuts.java 11/11
[top][prev][next]
package examples;
/**
* Demonstrate use of shortcuts
*
* Pre-operator (i.e., ++i or --i): operation is performed and value is produced
* Post-operator (i.e., i++ or i--), value is produced, then operation is performed
*
* @author sprenkle
*
*/
public class TestShortcuts {
public static void main(String[] args) {
int i = 1;
System.out.println("i : " + i); // Output: 1
System.out.println("++i : " + ++i); // Pre-increment: 2
System.out.println("i++ : " + i++); // Post-increment: 2
System.out.println("i : " + i); // 3
System.out.println("--i : " + --i); // Pre-decrement: 2
System.out.println("i-- : " + i--); // Post-decrement: 2
System.out.println("i : " + i); // 1
}
}
Generated by GNU enscript 1.6.4.