//******************************************************************** // Driver.java // Represents the driver of a bus //******************************************************************** public class Driver { private String name; private int age; private boolean isRisky; public Driver(String n, int a, boolean r) { name = n; age = a; isRisky = r; } //Indicate wether the driver is asleep at the wheel or not //Only a risk-taking driver may fall asleep at the wheel public boolean isAsleep() { int rand = (int)(Math.random()*2); return ((rand==0) && isRisky); } //Make a decision about allowing numPassengers passengers to get on //Result depends on the type of driver (risk-taking or not) public boolean acceptPassenger(int numSeats, int numPassengers) { boolean decision; if (!isRisky && (numPassengers+1>numSeats)) decision = false; else decision = true; return decision; } public boolean isRiskTaking() { return isRisky; } //Indicate the driver's info as a String public String toString() { String info = name + " , " + age + " years old.\n"; info += "a.k.a. " + ((isRisky) ? "2 fast 2 furious" : "Miss Daisy's driver"); return info; } } //******************************************************************** // Bus.java // Aggregate class containing a Driver object //******************************************************************** import java.text.DecimalFormat; public class Bus { private int maxSpeed; private int numSeats; private int numPassengers; private Driver theDriver; //no need to import class since part of same package public Bus(int speed, int seats, int passengers, Driver drive) { maxSpeed = speed; numSeats = seats; numPassengers = passengers; theDriver = drive; } //Drop off numPass passengers only if possible public void dropOff(int numPass) { int droppedOff = 0; if ( (numPass > numPassengers) || (numPass < 0) ) System.out.println("Unable to produce anti-matter."); else droppedOff = numPass; numPassengers -= droppedOff; System.out.println("Dropped off " + droppedOff + " passengers."); } //Try to pick up numPass passengers //Prints out how many were picked up (depending on Driver) public void pickUp(int numPass) { int pickedUp = 0; while (pickedUp < numPass) { boolean accept = theDriver.acceptPassenger(numSeats,numPassengers); if (!accept) break; pickedUp++; numPassengers++; } System.out.println("Picked up " + pickedUp + " passengers."); } //Try to travel numKm kilometers with bus //and print out the time taken to finish the trip //The result depends on the type of driver and the state of bus public void travel(int numKm) { DecimalFormat fmt = new DecimalFormat("0.#"); if (maxSpeed <= 0) //if bus is already out of service, don't travel System.out.println("This bus is out of service..."); else if (theDriver.isRiskTaking()) //if driver is risk-taking { if (theDriver.isAsleep()) //and falls asleep at the wheel, then crash the bus { System.out.println("CRRRRAAASSSSSHHHHHHHH!"); System.out.println("Hey! Who put that river there?"); numSeats = 0; //to indicate that the bus is no longer in service maxSpeed = 0; //to indicate that the bus is no longer in service } else //otherwise travel at maximum speed { double timeTaken = (double)numKm/maxSpeed; System.out.println(numKm + " km traveled in " + fmt.format(timeTaken) + " hours."); } } else //if driver is not risk-taking { if (numPassengers>numSeats) //and the number of passengers is more than allowed System.out.println("Get off my roof, I'm not moving."); //then don't travel else //otherwise travel at average speed { double timeTaken = numKm/(maxSpeed/2.0); System.out.println(numKm + " km traveled in " + fmt.format(timeTaken) + " hours."); } } } //Keep the passengers, just change the driver public void changeDriver(Driver newDriver) { theDriver = newDriver; } //Indicate the current state of the bus as a String (including state of driver) public String toString() { String info = theDriver.toString() + "\n"; info += "drives a bus of " + numSeats + " seats and "; info += numPassengers + " passengers,"; info += "which has a maximum speed of " + maxSpeed + " km/h."; return info; } } //******************************************************************** // QuebecBusTour.java // driver class to test classes Driver and Bus //******************************************************************** public class QuebecBusTour { public static void main (String[] args) { Driver coburn = new Driver("Hoke Coburn",44,false); Bus magicBus = new Bus(140,50,40,coburn); System.out.println(magicBus); System.out.println("\n40 passengers want to get on:"); magicBus.pickUp(40); System.out.println("\nTravel from Montreal to Quebec city:"); magicBus.travel(280); System.out.println("\nEvery passenger wants to get off:"); magicBus.dropOff(50); Driver oconner = new Driver("Brian O\'Conner",32,true); System.out.println("\nSwitch driver to:"); System.out.println(oconner); magicBus.changeDriver(oconner); System.out.println("\n80 passengers want to get on:"); magicBus.pickUp(80); System.out.println("\nTravel from Quebec city to Sherbrooke:"); magicBus.travel(210); System.out.println("\nTravel from Sherbrooke back to Montreal:"); magicBus.travel(150); } } //******************************************************************** // Rational.java Author: Lewis and Loftus // // Represents one rational number with a numerator and denominator. //******************************************************************** public class Rational { private int numerator, denominator; //----------------------------------------------------------------- // Sets up the rational number by ensuring a nonzero denominator // and making only the numerator signed. //----------------------------------------------------------------- public Rational (int numer, int denom) { if (denom == 0) denom = 1; // Make the numerator "store" the sign if (denom < 0) { numer = numer * -1; denom = denom * -1; } numerator = numer; denominator = denom; reduce(); } //----------------------------------------------------------------- // Adds this rational number to the one passed as a parameter. // A common denominator is found by multiplying the individual // denominators. //----------------------------------------------------------------- public Rational add (Rational op2) { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int sum = numerator1 + numerator2; return new Rational (sum, commonDenominator); } //----------------------------------------------------------------- // Subtracts the rational number passed as a parameter from this // rational number. //----------------------------------------------------------------- public Rational subtract (Rational op2) { int commonDenominator = denominator * op2.getDenominator(); int numerator1 = numerator * op2.getDenominator(); int numerator2 = op2.getNumerator() * denominator; int difference = numerator1 - numerator2; return new Rational (difference, commonDenominator); } //----------------------------------------------------------------- // Multiplies this rational number by the one passed as a // parameter. //----------------------------------------------------------------- public Rational multiply (Rational op2) { int numer = numerator * op2.getNumerator(); int denom = denominator * op2.getDenominator(); return new Rational (numer, denom); } //----------------------------------------------------------------- // Divides this rational number by the one passed as a parameter // by multiplying by the reciprocal of the second rational. //----------------------------------------------------------------- public Rational divide (Rational op2) { return multiply (op2.reciprocal()); } //----------------------------------------------------------------- // Returns the reciprocal of this rational number. //----------------------------------------------------------------- public Rational reciprocal () { return new Rational (denominator, numerator); } //----------------------------------------------------------------- // Returns the numerator of this rational number. //----------------------------------------------------------------- public int getNumerator () { return numerator; } //----------------------------------------------------------------- // Returns the denominator of this rational number. //----------------------------------------------------------------- public int getDenominator () { return denominator; } //----------------------------------------------------------------- // Determines if this rational number is equal to the one passed // as a parameter. Assumes they are both reduced. //----------------------------------------------------------------- public boolean equals (Rational op2) { return ( numerator == op2.getNumerator() && denominator == op2.getDenominator() ); } //----------------------------------------------------------------- // Returns this rational number as a string. //----------------------------------------------------------------- public String toString () { String result; if (numerator == 0) result = "0"; else if (denominator == 1) result = numerator + ""; else result = numerator + "/" + denominator; return result; } //----------------------------------------------------------------- // Reduces this rational number by dividing both the numerator // and the denominator by their greatest common divisor. //----------------------------------------------------------------- private void reduce () { if (numerator != 0) { int common = gcd (Math.abs(numerator), denominator); numerator = numerator / common; denominator = denominator / common; } } //----------------------------------------------------------------- // Computes and returns the greatest common divisor of the two // positive parameters. Uses Euclid's algorithm. //----------------------------------------------------------------- private int gcd (int num1, int num2) { while (num1 != num2) if (num1 > num2) num1 = num1 - num2; else num2 = num2 - num1; return num1; } } //******************************************************************** // RationalNumbers.java Author: Lewis and Loftus // // Driver to exercise the use of multiple Rational objects. //******************************************************************** public class RationalNumbers { //----------------------------------------------------------------- // Creates some rational number objects and performs various // operations on them. //----------------------------------------------------------------- public static void main (String[] args) { Rational r1 = new Rational (6, 8); Rational r2 = new Rational (1, 3); System.out.println ("First rational number: " + r1); System.out.println ("Second rational number: " + r2); if (r1.equals(r2)) System.out.println ("r1 and r2 are equal."); else System.out.println ("r1 and r2 are NOT equal."); Rational r3 = r1.add(r2); Rational r4 = r1.subtract(r2); Rational r5 = r1.multiply(r2); Rational r6 = r1.divide(r2); System.out.println ("r1 + r2: " + r3); System.out.println ("r1 - r2: " + r4); System.out.println ("r1 * r2: " + r5); System.out.println ("r1 / r2: " + r6); } } //******************************************************************** // TheProudMotherCat.java // Demonstrates the use of static variables //******************************************************************** public class TheProudMotherCat { public static void main (String[] args) { Cat frisky = new Cat(3,4.9f,true); System.out.println("There is " + Cat.numCats + " cat in the house."); System.out.println("Let's check out Frisky's stats:"); System.out.println(frisky); System.out.println("Frisky is about to give birth..."); Cat curly = frisky.giveBirth(); Cat larry = frisky.giveBirth(); Cat moe = frisky.giveBirth(); System.out.println("There are now " + Cat.numCats + " cats in the house."); System.out.println("Let's check out Frisky's stats:"); System.out.println(frisky); } } //******************************************************************** // Cat.java // Demonstrates the use of static variables //******************************************************************** public class Cat { private float weight; private int age; private boolean isFriendly; private static final float KITTENWEIGHT = 0.5f; public static int numCats = 0; public Cat(int catAge, float catWeight, boolean friendlyCat) { weight = catWeight; age = catAge; isFriendly = friendlyCat; numCats++; } public void moodSwing() { isFriendly = ((int)(Math.random()*2) == 0); } public String toString() { String sWeight = "I weight " + weight + " kg.\n"; String sAge = "I'm " + age + " years old.\n"; String sFriendly = (isFriendly)? "I'm the nicest cat in the world." : "One more step and I'll attack."; return (sWeight+sAge+sFriendly); } public Cat giveBirth() { wail(); weight -= KITTENWEIGHT; return new Cat(0,KITTENWEIGHT,true); } public float eat(float food) { weight += food; System.out.println("it wasn't Fancy Feast's seafood fillet..."); wail(); return weight; } public void wail() { System.out.println("Miiiiaaawwwwwww!"); moodSwing(); } } //******************************************************************** // ComparingCats.java // Demonstrates the difference between static and instance methods //******************************************************************** public class ComparingCats { public static void main (String[] args) { Cat frisky = new Cat(3,3.4f,true); Cat misty = new Cat(5,3.2f,false); System.out.println("There are " + Cat.getNumCats() + " cats in the house."); System.out.println("\nLet's check out Frisky's stats:"); System.out.println(frisky); System.out.println("\nLet's check out Misty's stats:"); System.out.println(misty); boolean isFriskyOlder = frisky.isOlder(misty); if (isFriskyOlder) System.out.println("\nFrisky is older than Misty."); else System.out.println("\nMisty is older than Frisky."); boolean isMistyHeavier = Cat.isHeavier(misty,frisky); if (isMistyHeavier) System.out.println("Misty is heavier than Frisky."); else System.out.println("Frisky is heavier than Misty."); } } //******************************************************************** // PigLatin.java // // Driver to exercise the PigLatinTranslator class. //******************************************************************** import java.util.Scanner; public class PigLatin { //----------------------------------------------------------------- // Reads sentences and translates them into Pig Latin. //----------------------------------------------------------------- public static void main (String[] args) { String sentence, result, another; Scanner scan = new Scanner(System.in); do { System.out.println (); System.out.println ("Enter a sentence (no punctuation):"); sentence = scan.nextLine(); System.out.println (); result = PigLatinTranslator.translate (sentence); System.out.println ("That sentence in Pig Latin is:"); System.out.println (result); System.out.println (); System.out.print ("Translate another sentence (y/n)? "); another = scan.nextLine(); } while (another.equalsIgnoreCase("y")); } } //******************************************************************** // PigLatinTranslator.java // // Represents a translation system from English to Pig Latin. // Demonstrates method decomposition and the use of StringTokenizer. //******************************************************************** import java.util.Scanner; public class PigLatinTranslator { //----------------------------------------------------------------- // Translates a sentence of words into Pig Latin. //----------------------------------------------------------------- public static String translate (String sentence) { String result = ""; sentence = sentence.toLowerCase(); Scanner scan = new Scanner (sentence); while (scan.hasNext()) { result += translateWord (scan.next()); result += " "; } return result; } //----------------------------------------------------------------- // Translates one word into Pig Latin. If the word begins with a // vowel, the suffix "yay" is appended to the word. Otherwise, // the first letter or two are moved to the end of the word, // and "ay" is appended. //----------------------------------------------------------------- private static String translateWord (String word) { String result = ""; if (beginsWithVowel(word)) result = word + "yay"; else if (beginsWithPrefix(word)) result = word.substring(2) + word.substring(0,2) + "ay"; else result = word.substring(1) + word.charAt(0) + "ay"; return result; } //----------------------------------------------------------------- // Determines if the specified word begins with a vowel. //----------------------------------------------------------------- private static boolean beginsWithVowel (String word) { String vowels = "aeiouAEIOU"; char letter = word.charAt(0); return (vowels.indexOf(letter) != -1); } //----------------------------------------------------------------- // Determines if the specified word begins with a particular // two-character prefix. //----------------------------------------------------------------- private static boolean beginsWithPrefix (String str) { return ( str.startsWith ("bl") || str.startsWith ("pl") || str.startsWith ("br") || str.startsWith ("pr") || str.startsWith ("ch") || str.startsWith ("sh") || str.startsWith ("cl") || str.startsWith ("sl") || str.startsWith ("cr") || str.startsWith ("sp") || str.startsWith ("dr") || str.startsWith ("sr") || str.startsWith ("fl") || str.startsWith ("st") || str.startsWith ("fr") || str.startsWith ("th") || str.startsWith ("gl") || str.startsWith ("tr") || str.startsWith ("gr") || str.startsWith ("wh") || str.startsWith ("kl") || str.startsWith ("wr") || str.startsWith ("ph") ); } } //******************************************************************** // SnakeEyes.java Author: Lewis and Loftus // // Demonstrates the use of a class with overloaded constructors. //******************************************************************** public class SnakeEyes { //----------------------------------------------------------------- // Creates two die objects, then rolls both dice a set number of // times, counting the number of snake eyes that occur. //----------------------------------------------------------------- public static void main (String[] args) { final int ROLLS = 500; int snakeEyes = 0, num1, num2; Die die1 = new Die(); // creates a six-sided die Die die2 = new Die(20); // creates a twenty-sided die for (int roll = 1; roll <= ROLLS; roll++) { num1 = die1.roll(); num2 = die2.roll(); if (num1 == 1 && num2 == 1) // check for snake eyes snakeEyes++; } System.out.println ("Number of rolls: " + ROLLS); System.out.println ("Number of snake eyes: " + snakeEyes); System.out.println ("Ratio: " + (float)snakeEyes/ROLLS); } } //******************************************************************** // Die.java Author: Lewis and Loftus // // Represents one die (singular of dice) with faces showing values // between 1 and the number of faces on the die. //******************************************************************** public class Die { private final int MIN_FACES = 4; private int numFaces; // number of sides on the die private int faceValue; // current value showing on the die //----------------------------------------------------------------- // Defaults to a six-sided die, initially showing 1. //----------------------------------------------------------------- public Die () { numFaces = 6; faceValue = 1; } //----------------------------------------------------------------- // Explicitly sets the size of the die. Defaults to a size of // six if the parameter is invalid. Initial face is 1. //----------------------------------------------------------------- public Die (int faces) { if (faces < MIN_FACES) numFaces = 6; else numFaces = faces; faceValue = 1; } //----------------------------------------------------------------- // Rolls the die and returns the result. //----------------------------------------------------------------- public int roll () { faceValue = (int) (Math.random() * numFaces) + 1; return faceValue; } //----------------------------------------------------------------- // Returns the current die value. //----------------------------------------------------------------- public int getFaceValue () { return faceValue; } } //*********************************************************************** // SimpleCat.java // Multiple constructors //*********************************************************************** public class SimpleCat { private float weight; private int age; private boolean isFriendly; public SimpleCat(int catAge, float catWeight, boolean friendlyCat) { weight = catWeight; age = catAge; isFriendly = friendlyCat; } public SimpleCat(int catAge, float catWeight) { weight = catWeight; age = catAge; moodSwing(); } public SimpleCat() { weight = 0.5f; age = 1; moodSwing(); } public void moodSwing() { isFriendly = ((int)(Math.random()*2) == 0); } public String toString() { String sWeight = "I weight " + weight + " kg.\n"; String sAge = "I'm " + age + " years old.\n"; String sFriendly = (isFriendly)? "I'm the nicest cat in the world." : "One more step and I'll attack."; return (sWeight+sAge+sFriendly); } public float eat(float food) { weight += food; System.out.println("it wasn't Fancy Feast's seafood fillet..."); wail(); return weight; } public void wail() { System.out.println("Miiiiaaawwwwwww!"); moodSwing(); } }