Presentation is loading. Please wait.

Presentation is loading. Please wait.

INF 523Q Chapter 4: Writing Classes (Examples). Coin.java b //****************************************************************** b // Coin.java Author:

Similar presentations


Presentation on theme: "INF 523Q Chapter 4: Writing Classes (Examples). Coin.java b //****************************************************************** b // Coin.java Author:"— Presentation transcript:

1 INF 523Q Chapter 4: Writing Classes (Examples)

2 Coin.java b //****************************************************************** b // Coin.java Author: Lewis and Loftus b // Represents a coin with two sides that can be flipped. b //****************************************************************** b public class Coin b { b public final int HEADS = 0; b public final int TAILS = 1; b private int face; b // Sets up the coin by flipping it initially. b public Coin () b { b flip(); b } b // Flips the coin by randomly choosing a face. b public void flip () b { b face = (int) (Math.random() * 2); b }

3 Coin.java (cont.) b // Returns the current face of the coin as an integer. b public int getFace () b { b return face; b } b // Returns the current face of the coin as a string. b public String toString() b { b String faceName; b if (face == HEADS) b faceName = "Heads"; b else b faceName = "Tails"; b return faceName; b }

4 CountFlips.java b //****************************************************************** b // CountFlips.java Author: Lewis and Loftus b // Demonstrates the use of a programmer-defined class. b //****************************************************************** b import Coin; b public class CountFlips b { b // Flips a coin multiple times and counts the number of heads and tails that result. b public static void main (String[] args) b { b final int NUM_FLIPS = 1000; b int heads = 0, tails = 0; b Coin myCoin = new Coin(); // instantiate the Coin object b for (int count=1; count <= NUM_FLIPS; count++)

5 CountFlips.java (cont.) b { b myCoin.flip(); b if (myCoin.getFace() == myCoin.HEADS) b heads++; b else b tails++; b } b System.out.println ("The number flips: " + NUM_FLIPS); b System.out.println ("The number of heads: " + heads); b System.out.println ("The number of tails: " + tails); b }

6 FlipRace.java b //******************************************************************** b // FlipRace.java Author: Lewis and Loftus b // Demonstrates the existence of separate data space in multiple b // instantiations of a programmer-defined class. b //******************************************************************** b import Coin; b public class FlipRace b { b // Flips two coins until one of them comes up heads a set number of times in a row. b public static void main (String[] args) b { b final int GOAL = 3; b int count1 = 0, count2 = 0; b // Create two separate coin objects b Coin coin1 = new Coin(); b Coin coin2 = new Coin(); b while (count1 < GOAL && count2 < GOAL) b { b coin1.flip(); b coin2.flip();

7 FlipRace.java (cont.) b // Print the flip results (uses Coin's toString method) b System.out.print ("Coin 1: " + coin1); b System.out.println (" Coin 2: " + coin2); b // Increment or reset the counters b count1 = (coin1.getFace() == coin1.HEADS) ? count1+1 : 0; b count2 = (coin2.getFace() == coin2.HEADS) ? count2+1 : 0; b } b // Determine the winner b if (count1 < GOAL) b System.out.println ("Coin 2 Wins!"); b else b if (count2 < GOAL) b System.out.println ("Coin 1 Wins!"); b else b System.out.println ("It's a TIE!"); b }

8 Account.java b //******************************************************************** b // Account.java Author: Lewis and Loftus b // Represents a bank account with basic services such as deposit and withdraw. b //******************************************************************** b import java.text.NumberFormat; b public class Account b { b private NumberFormat fmt = NumberFormat.getCurrencyInstance(); b private final double RATE = 0.045; // interest rate of 4.5% b private long acctNumber; b private double balance; b private String name; b // Sets up the account by defining its owner, account number, b // and initial balance. b public Account (String owner, long account, double initial) b { b name = owner; b acctNumber = account; b balance = initial; b }

9 Account.java (cont.) b // Validates the transaction, then deposits the specified amount b // into the account. Returns the new balance. b public double deposit (double amount) b { b if (amount < 0) // deposit value is negative b { b System.out.println (); b System.out.println ("Error: Deposit amount is invalid."); b System.out.println (acctNumber + " " + fmt.format(amount)); b } b else b balance = balance + amount; b return balance; b } b // Validates the transaction, then withdraws the specified amount b // from the account. Returns the new balance. b public double withdraw (double amount, double fee) b { b amount += fee;

10 Account.java (cont.) b if (amount < 0) // withdraw value is negative b { b System.out.println (); b System.out.println ("Error: Withdraw amount is invalid."); b System.out.println ("Account: " + acctNumber); b System.out.println ("Requested: " + fmt.format(amount)); b } b else b if (amount > balance) // withdraw value exceeds balance b { b System.out.println (); b System.out.println ("Error: Insufficient funds."); b System.out.println ("Account: " + acctNumber); b System.out.println ("Requested: " + fmt.format(amount)); b System.out.println ("Available: " + fmt.format(balance)); b } b else b balance = balance - amount; b return balance; b }

11 Account.java (cont.) b // Adds interest to the account and returns the new balance. b public double addInterest () b { b balance += (balance * RATE); b return balance; b } b // Returns the current balance of the account. b public double getBalance () b { b return balance; b } b // Returns the account number. b public long getAccountNumber () b { b return acctNumber; b } b // Returns a one-line description of the account as a string. b public String toString () b { b return (acctNumber + "\t" + name + "\t" + fmt.format(balance)); } }

12 BankAccounts.java b //******************************************************************** b // BankAccounts.java Author: Lewis and Loftus b // Driver to exercise the use of multiple Account objects. b //******************************************************************** b import Account; b public class BankAccounts b { b // Creates some bank accounts and requests various services. b public static void main (String[] args) b { b Account acct1 = new Account ("Ted Murphy", 72354, 102.56); b Account acct2 = new Account ("Jane Smith", 69713, 40.00); b Account acct3 = new Account ("Edward Demsey", 93757, 759.32); b acct1.deposit (25.85); b double smithBalance = acct2.deposit (500.00); b System.out.println ("Smith balance after deposit: " + b smithBalance);

13 BankAccounts.java (cont.) b System.out.println ("Smith balance after withdrawal: " + b acct2.withdraw (430.75, 1.50)); b acct3.withdraw (800.00, 0.0); // exceeds balance b acct1.addInterest(); b acct2.addInterest(); b acct3.addInterest(); b System.out.println (); b System.out.println (acct1); b System.out.println (acct2); b System.out.println (acct3); b }

14 Rational.java b //******************************************************************** b // Rational.java Author: Lewis and Loftus b // Represents one rational number with a numerator and denominator. b //******************************************************************** b public class Rational b { b private int numerator, denominator; b // Sets up the rational number by ensuring a nonzero denominator b // and making only the numerator signed. b public Rational (int numer, int denom) b { b if (denom == 0) b denom = 1; b // Make the numerator "store" the sign b if (denom < 0) b { b numer = numer * -1; b denom = denom * -1; b } b numerator = numer; b denominator = denom; b reduce(); }

15 Rational.java (cont.) b // Adds this rational number to the one passed as a parameter. b // A common denominator is found by multiplying the individual b // denominators. b public Rational add (Rational op2) b { b int commonDenominator = denominator * op2.getDenominator(); b int numerator1 = numerator * op2.getDenominator(); b int numerator2 = op2.getNumerator() * denominator; b int sum = numerator1 + numerator2; b return new Rational (sum, commonDenominator); b } b // Subtracts the rational number passed as a parameter from this b // rational number. b public Rational subtract (Rational op2) b { b int commonDenominator = denominator * op2.getDenominator(); b int numerator1 = numerator * op2.getDenominator(); b int numerator2 = op2.getNumerator() * denominator; b int difference = numerator1 - numerator2; b return new Rational (difference, commonDenominator); b }

16 Rational.java (cont.) b // Multiplies this rational number by the one passed as a parameter. b public Rational multiply (Rational op2) b { b int numer = numerator * op2.getNumerator(); b int denom = denominator * op2.getDenominator(); b return new Rational (numer, denom); b } b // Divides this rational number by the one passed as a parameter b // by multiplying by the reciprocal of the second rational. b public Rational divide (Rational op2) b { b return multiply (op2.reciprocal()); b } b // Returns the reciprocal of this rational number. b public Rational reciprocal () b { b return new Rational (denominator, numerator); b } b // Returns the numerator of this rational number. b public int getNumerator () b { return numerator; }

17 Rational.java (cont.) b // Returns the denominator of this rational number. b public int getDenominator () b { return denominator; } b // Determines if this rational number is equal to the one passed b // as a parameter. Assumes they are both reduced. b public boolean equals (Rational op2) b { b return ( numerator == op2.getNumerator() && b denominator == op2.getDenominator() ); b } b // Returns this rational number as a string. b public String toString () b { b String result; b if (numerator == 0) b result = "0"; b else b if (denominator == 1) b result = numerator + ""; b else b result = numerator + "/" + denominator; b return result; }

18 Rational.java (cont.) b // Reduces this rational number by dividing both the numerator b // and the denominator by their greatest common divisor. b private void reduce () b { b if (numerator != 0) b { b int common = gcd (Math.abs(numerator), denominator); b numerator = numerator / common; b denominator = denominator / common; b } b // Computes and returns the greatest common divisor of the two b // positive parameters. Uses Euclid's algorithm. b private int gcd (int num1, int num2) b { b while (num1 != num2) b if (num1 > num2) b num1 = num1 - num2; b else b num2 = num2 - num1; b return num1; b } }

19 RationalNumbers.java b //******************************************************************** b // RationalNumbers.java Author: Lewis and Loftus b // Driver to exercise the use of multiple Rational objects. b //******************************************************************** b import Rational; b public class RationalNumbers b { b // Creates some rational number objects and performs various b // operations on them. b public static void main (String[] args) b { b Rational r1 = new Rational (6, 8); b Rational r2 = new Rational (1, 3); b System.out.println ("First rational number: " + r1); b System.out.println ("Second rational number: " + r2);

20 RationalNumbers.java (cont.) b if (r1.equals(r2)) b System.out.println ("r1 and r2 are equal."); b else b System.out.println ("r1 and r2 are NOT equal."); b Rational r3 = r1.add(r2); b Rational r4 = r1.subtract(r2); b Rational r5 = r1.multiply(r2); b Rational r6 = r1.divide(r2); b System.out.println ("r1 + r2: " + r3); b System.out.println ("r1 - r2: " + r4); b System.out.println ("r1 * r2: " + r5); b System.out.println ("r1 / r2: " + r6); b }

21 Die.java b //******************************************************************** b // Die.java Author: Lewis and Loftus b // Represents one die (singular of dice) with faces showing values b // between 1 and the number of faces on the die. b //******************************************************************** b public class Die b { b private final int MIN_FACES = 4; b b private int numFaces; // number of sides on the die b private int faceValue; // current value showing on the die b b // Defaults to a six-sided die, initially showing 1. b public Die () b { b numFaces = 6; b faceValue = 1; b }

22 Die.java (cont.) b // Explicitly sets the size of the die. Defaults to a size of b // six if the parameter is invalid. Initial face is 1. b public Die (int faces) b { b if (faces < MIN_FACES) b numFaces = 6; b else b numFaces = faces; b faceValue = 1; b } b // Rolls the die and returns the result. b public int roll () b { b faceValue = (int) (Math.random() * numFaces) + 1; b return faceValue; b } b // Returns the current die value. b public int getFaceValue () b { b return faceValue; } }

23 SnakeEyes.java b //******************************************************************** b // SnakeEyes.java Author: Lewis and Loftus b // Demonstrates the use of a class with overloaded constructors. b //******************************************************************** b import Die; b public class SnakeEyes b { // Creates two die objects, then rolls both dice a set number of b // times, counting the number of snake eyes that occur. b public static void main (String[] args) b { final int ROLLS = 500; b int snakeEyes = 0, num1, num2; b Die die1 = new Die(); // creates a six-sided die b Die die2 = new Die(20); // creates a twenty-sided die b for (int roll = 1; roll <= ROLLS; roll++) b { num1 = die1.roll(); b num2 = die2.roll(); b if (num1 == 1 && num2 == 1) // check for snake eyes b snakeEyes++; b } b System.out.println ("Number of rolls: " + ROLLS); b System.out.println ("Number of snake eyes: " + snakeEyes); b System.out.println ("Ratio: " + (float)snakeEyes/ROLLS); } }

24 PigLatinTranslator.java b b //******************************************************************** b b // PigLatinTranslator.java Author: Lewis and Loftus b b // Represents a translation system from English to Pig Latin. b b // Demonstrates method decomposition and the use of StringTokenizer. b b //******************************************************************** b b import java.util.StringTokenizer; b b public class PigLatinTranslator bb{bb{ b b // Translates a sentence of words into Pig Latin. b b public String translate (String sentence) b b { b b String result = ""; b b sentence = sentence.toLowerCase(); b b StringTokenizer tokenizer = new StringTokenizer (sentence); bb bb b b while (tokenizer.hasMoreTokens()) b b { b b result += translateWord (tokenizer.nextToken()); b b result += " "; b b } b b return result; }

25 PigLatinTranslator.java (cont.) b // Translates one word into Pig Latin. If the word begins with a vowel, the suffix "yay“ b // is appended to the word. Otherwise, the first letter or two are moved to the end of b // the word, and "ay" is appended. b private String translateWord (String word) b { b String result = ""; b if (beginsWithVowel(word)) b result = word + "yay"; b else b if (beginsWithPrefix(word)) b result = word.substring(2) + word.substring(0,2) + "ay"; b else b result = word.substring(1) + word.charAt(0) + "ay"; b return result; b } b // Determines if the specified word begins with a vowel. b private boolean beginsWithVowel (String word) b { b String vowels = "aeiouAEIOU"; b char letter = word.charAt(0); b return (vowels.indexOf(letter) != -1); }

26 PigLatinTranslator.java (cont.) b // Determines if the specified word begins with a particular two-character prefix. b private boolean beginsWithPrefix (String str) b { b return ( str.startsWith ("bl") || str.startsWith ("pl") || b str.startsWith ("br") || str.startsWith ("pr") || b str.startsWith ("ch") || str.startsWith ("sh") || b str.startsWith ("cl") || str.startsWith ("sl") || b str.startsWith ("cr") || str.startsWith ("sp") || b str.startsWith ("dr") || str.startsWith ("sr") || b str.startsWith ("fl") || str.startsWith ("st") || b str.startsWith ("fr") || str.startsWith ("th") || b str.startsWith ("gl") || str.startsWith ("tr") || b str.startsWith ("gr") || str.startsWith ("wh") || b str.startsWith ("kl") || str.startsWith ("wr") || b str.startsWith ("ph") ); b }

27 PigLatin.java b //****************************************************************** b // PigLatin.java Author: Lewis and Loftus b // Driver to exercise the PigLatinTranslator class. b //****************************************************************** b import PigLatinTranslator; b import cs1.Keyboard; b public class PigLatin b { b // Reads sentences and translates them into Pig Latin. b public static void main (String[] args) b { b String sentence, result, another; b PigLatinTranslator translator = new PigLatinTranslator();

28 PigLatin.java (cont.) b do b { b System.out.println (); b System.out.println ("Enter a sentence (no punctuation):"); b sentence = Keyboard.readString(); b System.out.println (); b result = translator.translate (sentence); b System.out.println ("That sentence in Pig Latin is:"); b System.out.println (result); b System.out.println (); b System.out.print ("Translate another sentence (y/n)? "); b another = Keyboard.readString(); b } b while (another.equalsIgnoreCase("y")); b }


Download ppt "INF 523Q Chapter 4: Writing Classes (Examples). Coin.java b //****************************************************************** b // Coin.java Author:"

Similar presentations


Ads by Google