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

Slides:



Advertisements
Similar presentations
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Advertisements

Java Software Solutions
Chapter 4: Writing Classes. 2 Objects  An object has: state - descriptive characteristics behaviors - what it can do (or what can be done to it)  For.
Chapter 4: Writing Classes
© 2006 Pearson Education Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science A 2nd Edition by John Lewis,
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Writing Classes The programs we’ve written in previous examples have.
Writing Classes in Java
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
Chapter 6 Object-Oriented Design. 6-2 Program Development The creation of software involves four basic activities:  establishing the requirements  creating.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Java Review Selim Aksoy Bilkent University Department of Computer Engineering
Foundations of Program Design Writing Classes. 2 Objects b An object has: state - descriptive characteristicsstate - descriptive characteristics behaviors.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Basic Concepts of OO An object has state: defined by the set of fields or attributes. behavior: defined by the set of methods (operations that can be applied.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Second Edition by John Lewis and William Loftus.
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Objects and Classes Objects and Classes objects defining classes method declaration object references and aliases instance variables encapsulation and.
Methods in Java Selim Aksoy Bilkent University Department of Computer Engineering
Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science by John Lewis, William Loftus, and Cara Cocking Java.
1 (c) elsaddik CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley John Lewis, Peter DePasquale, and Joseph Chase Chapter 5: Writing Classes.
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved2/48 Writing Classes We've been using predefined classes. Now we will learn.
Writing Classes (Chapter 4)
Writing Classes Chapter 5 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
Writing Classes Chapter 5 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013.
The this Reference The this reference, used inside a method, refers to the object through which the method is being executed Suppose the this reference.
Objects and Classes. Problem Solving The key to designing a solution is breaking it down into manageable pieces When writing software, we design separate.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Chapter 6 Object-Oriented Design Part 1. © 2004 Pearson Addison-Wesley. All rights reserved2/42 Object-Oriented Design Now we can extend our discussion.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CSE 1201 Object Oriented Programming Writing Classes.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CSE 1201 Object Oriented Programming Object Oriented Design.
COS 312 DAY 7 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Due – 2 MIA Capstones proposals due – 1 group proposal for 4 student Assignment 3 Posted.
Wednesday –POD –I have updated grades in powerschool. If you have a zero for a lab grade, it probably means you didn’t DropItToMe. Please do so. –Slides.
Lecture 4 b Writing Classes b class declarations b method declarations b constructors b instance variables b encapsulation b method overloading b program.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
INF 523Q Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter.
Chapter 4: Writing Classes. 2 b We've been using predefined classes. Now we will learn to write our own classes to define new objects b Chapter 4 focuses.
Programming in Java (COP 2250) Lecture 10 Chengyong Yang Fall, 2005.
Chapter 4 Writing Classes. © 2004 Pearson Addison-Wesley. All rights reserved4-2 Writing Classes We've been using predefined classes. Now we will learn.
Copyright © 2012 Pearson Education, Inc. Chapter 4 Writing Classes Java Software Solutions Foundations of Program Design Seventh Edition John Lewis William.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 4: Writing Classes Presentation slides for Java Software Solutions for AP* Computer Science.
Outline Software Development Activities Identifying Classes and Objects Static Variables and Methods Class Relationships Interfaces Enumerated Types Revisited.
Outline Anatomy of a Class Encapsulation Anatomy of a Method Graphical Objects Graphical User Interfaces Buttons and Text Fields Copyright © 2012 Pearson.
1 Chapter 4: Writing Classes  Chapter 4 focuses on: class definitions encapsulation and Java modifiers method declaration, invocation, and parameter passing.
COS 312 DAY 6 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Posted – Due Feb 22 prior to class Assignment 3 posted – March 5 Prior to class Capstones.
COS 312 DAY 7 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Not corrected yet – Will be done later today Capstones proposals Over due – 1 received.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
COS 312 DAY 8 Tony Gauvin. Ch 1 -2 Agenda Questions? Assignment 2 Corrected – Great results Capstones proposals Over due – 2 received Capstone progress.
University of Turkish Aeronautical Association Computer Engineering Department CENG 112 COMPUTER PROGRAMMING 2 Tansel Dökeroglu, Ph.D.
Chapter 4: Writing Classes
Chapter 4: Writing Classes
Writing Classes Chapter 4.
Writing Classes We've been using predefined classes from the Java API. Now we will learn to write our own classes. Chapter 4 focuses on: class definitions.
Chapter 5 – Writing Classes
Chapter 4: Writing Classes
Chapter 5 – Writing Classes
Chapter 5 – Writing Classes
Outline Boolean Expressions The if Statement Comparing Data
Chapter 4 Writing Classes
Anatomy of a Method.
Writing Classes.
Chapter 4: Writing Classes
Presentation transcript:

INF 523Q Chapter 4: Writing Classes (Examples)

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 }

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 }

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++)

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 }

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();

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 }

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 }

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;

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 }

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)); } }

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, ); b Account acct2 = new Account ("Jane Smith", 69713, 40.00); b Account acct3 = new Account ("Edward Demsey", 93757, ); b acct1.deposit (25.85); b double smithBalance = acct2.deposit (500.00); b System.out.println ("Smith balance after deposit: " + b smithBalance);

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 }

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(); }

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 }

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; }

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; }

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 } }

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);

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 }

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 }

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; } }

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); } }

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; }

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); }

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 }

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();

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 }