Download presentation
Presentation is loading. Please wait.
Published byJulian Lester Modified over 8 years ago
1
Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 7 Writing Your Own Classes Writing New Classes Parameters Example: A Money Class Writing Well-Designed Classes Class Methods and Variables Computer Networks
2
Programming and Problem Solving With Java 2 Writing New Classes Package related group of methods Example: Math class Use methods with name of the class int x = Math.abs(y); Make a new data type Example: Turtle class Make an object of the class Turtle myTurtle = new Turtle(); Use methods with objects myTurtle.move(100);
3
Programming and Problem Solving With Java 3 Writing New Classes To model real-world object that doesn't correspond to existing class or type, either Adjust view of real-world object: make it fit into existing class or type Create a new type that fits the real-world object
4
Programming and Problem Solving With Java 4 Writing New Classes Adjust view of real-world object: make it fit into existing class or type Example: use double to store money Probably not a perfect fit Quick and simple for small programs Resulting program not as easy to understand
5
Programming and Problem Solving With Java 5 Writing New Classes Create a new type that fits the real-world object More effort initially Resulting program easier to understand Usually the best approach for most programs
6
Programming and Problem Solving With Java 6 Writing New Classes First step for class design: choose operations (methods) Helps specify purpose of class Example: suppose no Integer or int in Java Operations for a new Integer class add() subtract() multiply() divide() remainder() set() get()
7
Programming and Problem Solving With Java 7 Writing New Classes Class operations provide access to object internals Can't get to private parts of object directly Benefits Can test operations as we write them Can substitute a new implementation Class provides organization to program Can reuse the class Object internals Operations Method call
8
Programming and Problem Solving With Java 8 Writing New Classes: Defining Class is template for objects Named group of methods and variables Objects share methods Each object has copy of variables class Counter { // Constructor: initializes the counter // to 0 public Counter() { value = 0; } // increment: Adds one to the counter's // value public void increment() { value++; } // getValue(): Returns the value of the // counter public int getValue() { return value; } // toString: Returns the value of the // counter as a string public String toString() { return String.valueOf(value); } private int value; }
9
Programming and Problem Solving With Java 9 Writing New Classes: Defining // Demonstrates use of the Counter class. import Counter; public class DemonstrateCounter { public static void main(String[] args) { // Make a new Counter object Counter aCounter = new Counter(); // Show the initial value of the object System.out.println("Initial value of counter is " + aCounter); // Loop ten times, incrementing the aCounter object // each time System.out.println("Starting loop..."); for (int i = 1; i <= 10; i++) { // Add one to the Counter object aCounter.increment(); System.out.println(" Counter is now " + aCounter); } System.out.println("Loop completed"); // Show the final value of the object int aCounterValue = aCounter.getValue(); System.out.println("Final value of counter is " + aCounterValue); }
10
Programming and Problem Solving With Java 10 Writing New Classes: Methods Method: named group of executable statements Belongs to a class Can access other methods and variables of the class Method signature Access (public, private) Return type (or void) Method name Parameters No two methods with same signature in one class // increment: Adds one to the // counter's value public void increment() { value++; } Method signature
11
Programming and Problem Solving With Java 11 Writing New Classes: Methods void Method No return value Specify with "void" in signature Definition (no parameters) // Comment that describes the method public void nameOfMethod() { statements; } Use Use as executable statement object.nameOfMethod(); Example definition class Counter {... // increment: Adds one to the counter's value public void increment() { value++; }... } Example use Counter aCounter = new Counter(); aCounter.increment();
12
Programming and Problem Solving With Java 12 Writing New Classes: Methods Typed Method Has return value Specify return type in signature Definition (no parameters) // Comment that describes the method public type nameOfMethod() { statements; return expression; } Use Use in an expression type x = object.nameOfMethod(); Example definition class Counter {... // getValue: Returns the value // of the counter public int getValue() { return value; }... } Example use Counter aCounter = new Counter(); int aCounterValue = aCounter.getValue();
13
Programming and Problem Solving With Java 13 Writing New Classes: Methods The toString() method Java uses toString() to convert objects to String Useful when displaying object values Without toString() SomeClass anObject = new SomeClass(); System.out.println(anObject); With toString() Counter aCounter = new Counter(); System.out.println(aCounter); No conversion to String: SomeClass has no toString() method SomeClass@1cc803 0 Automatic conversion to String: Counter has a toString() method
14
Programming and Problem Solving With Java 14 Writing New Classes: Constructor Constructor Special method that initializes an object's variables Has same name as class, no return type Computer executes on object when it creates the object Example // Constructor: initializes the counter // to 0 public Counter() { value = 0; } Use of constructor Counter aCounter = new Counter(); Default constructor : no parameters Automatic constructor: default (does nothing) Use of constructor
15
Programming and Problem Solving With Java 15 Parameters Can send information to a method System.out.println("Hello"); int x = Math.abs(y); myTurtle.turnRight(90); Parameter Like local variable, but gets initial value from caller Actual parameter Value passed to method Also called argument Formal parameter Name used in method Also called parameter
16
Programming and Problem Solving With Java 16 Parameters Actual parameter DemonstrateParameter myObject = new DemonstrateParameter(); myObject.voidMethod(123); Formal parameter class DemonstrateParameter { // voidMethod: Displays the value of aParameter public void voidMethod(int aParameter) { System.out.println("voidMethod argument is " + aParameter); } // typedMethod: Displays the value of aParameter, then // returns aParameter + 1 public int typedMethod(int aParameter) { System.out.println("typedMethod argument is " + aParameter); return aParameter + 1; } Value 123 passed to voidMethod()
17
Programming and Problem Solving With Java 17 Parameters: More than One Method can have any number of parameters class DemonstrateTwoParameters { // displaySum: Displays the sum of its two arguments public void displaySum(int firstParameter, int secondParameter) { System.out.println("The sum of " + firstParameter + " and " + secondParameter + " is " + (firstParameter + secondParameter)); } public class TestDemonstrateTwoParameters { public static void main(String[] args) { DemonstrateTwoParameters myObject = new DemonstrateTwoParameters(); myObject.displaySum(100, 200); } Values passed in order to displaySum()
18
Programming and Problem Solving With Java 18 Parameters: More than One Rules with parameters Number of actual parameters = number of formal parameters Type of each actual parameter = type of corresponding formal parameter Examples Signature public void displaySum(int firstParameter, int secondParameter) Valid call myObject.displaySum(100, 200); Invalid calls myObject.displaySum(200); // Wrong: Not enough actuals myObject.displaySum(100, 200, 300); // Wrong: Too many actuals myObject.displaySum(123.45, 67.1); // Wrong: Needs two integers
19
Programming and Problem Solving With Java 19 Constructors with Parameters Constructor can have parameters public class Counter { // Constructor: initializes the counter to the given argument public Counter(int value) { this.value = value; }... } Must use parameter when creating object import Counter; public class DemonstrateCounter { public static void main(String[] args) { Counter firstCounter = new Counter(0); // Start counter at 0 Counter secondCounter = new Counter(12); // Start counter at 12 firstCounter.increment(); secondCounter.increment();... }
20
Programming and Problem Solving With Java 20 Constructors with Parameters Can make parameter optional Provide two constructors: one with parameter, one without (default constructor) public class Counter { // Default Constructor: initializes the counter to 0 public Counter() { value = 0; } // Constructor: initializes the counter to the given argument public Counter(int value) { this.value = value; }... }
21
Programming and Problem Solving With Java 21 Constructors with Parameters Better way to write two constructors Have one do the work, the other calls it Makes code more centralized -- easier to manage public class Counter { // Default Constructor: initializes the counter to 0 public Counter() { this(0); } // Constructor: initializes the counter to the given argument public Counter(int value) { this.value = value; }... } How to call one constructor from another
22
Programming and Problem Solving With Java 22 Constructors with Parameters Java compiler knows which constructor to use by the arguments public class DemonstrateCounter { public static void main(String[] args) { Counter firstCounter = new Counter(); // Start counter at 0 Counter secondCounter = new Counter(12); // Start counter at 12 firstCounter.increment(); secondCounter.increment();... } Use default constructor Use constructor with argument
23
Programming and Problem Solving With Java 23 Example: Money Class Floating-point types not appropriate for currency Round-off error unacceptable Design our own Money class with these operations getDollars()Return dollars of this Money object getCents()Return cents of this Money object add() Return this Money object + another subtract()Return this Money object - another multiply()Return this Money object * integer equal()Return true if this object == another less()Return true if this object < another toString()Return value as a String setAmount()Change value of this Money object Constructors
24
Programming and Problem Solving With Java 24 Example: Money Class Want result to be like "Money calculator" User uses operations, not internals
25
Programming and Problem Solving With Java 25 Example: Money Class Example of Money class use // Demonstrates use of the Money class. The program // displays the sum of 12.50 and 3.75. import Money; public class DemonstrateMoney { public static void main(String[] args) { Money total; Money firstValue = new Money(12, 50); Money secondValue = new Money(3, 75); // Compute the sum of 12.50 and 3.75 total = firstValue.add(secondValue); System.out.println("12.50 + 3.75 is " + total); } Shorter version Money total = new Money(12,50).add(new Money(3,75)); System.out.println("12.50 + 3.75 is " + total);
26
Programming and Problem Solving With Java 26 Example: Money Class (1) // The Money class. Each Money object stores dollars // and cents. public class Money { // Default Constructor: Initializes a new Money object to 0 public Money() { this(0, 0); } // Constructor: Initializes a new Money object to the given // amount public Money(int dollars, int cents) { setAmount(dollars, cents); } // setAmount: Assigns a new value to a Money object public void setAmount(int dollars, int cents) { this.dollars = dollars; this.cents = cents; normalize(); }
27
Programming and Problem Solving With Java 27 Example: Money Class (2) // getDollars: Returns the number of dollars in this object public int getDollars() { return dollars; } // getCents: Returns the number of cents in this object public int getCents() { return cents; } // toString: Converts the value in this object to string // format, for example: 123.45 // If the value is negative, displays the // negative sign after the number: 123.45- public String toString() { String result = Math.abs(dollars) + "."; if (Math.abs(cents) < 10) { result = result + "0"; } result = result + Math.abs(cents); if (dollars < 0 || cents < 0) { result = result + "-"; } return result; }
28
Programming and Problem Solving With Java 28 Example: Money Class (3) // add: Returns the sum of this Money object and another Money // object public Money add(Money otherMoneyObject) { return new Money(dollars + otherMoneyObject.getDollars(), (cents + otherMoneyObject.getCents())); } // subtract: Returns the difference of this Money object and // another Money object public Money subtract(Money otherMoneyObject) { return new Money(dollars - otherMoneyObject.getDollars(), (cents - otherMoneyObject.getCents())); } // multiply: Returns the product of this Money object and an // integer multiplier public Money multiply(int multiplier) { return new Money(dollars * multiplier, (cents * multiplier)); }
29
Programming and Problem Solving With Java 29 Example: Money Class (4) // equals: Returns true if this Money object is equal to // another, otherwise false public boolean equals(Money otherMoneyObject) { return dollars == otherMoneyObject.getDollars() && cents == otherMoneyObject.getCents(); } // less: Returns true if this Money object is less than another, // otherwise false public boolean less(Money otherMoneyObject) { return dollars < otherMoneyObject.dollars || (dollars == otherMoneyObject.getDollars() && cents < otherMoneyObject.getCents()); }
30
Programming and Problem Solving With Java 30 Example: Money Class (5) // normalize: Adjusts the dollars and cents so the cents is // between +0 and +99. private void normalize() { dollars = dollars + cents / 100; cents = cents % 100; if (dollars > 0 && cents < 0) { dollars--; cents = cents + 100; } else if (dollars 0) { dollars++; cents = cents - 100; } // Instance variables private int dollars; private int cents; }
31
Programming and Problem Solving With Java 31 Example: Money Class Another example of use // Another demonstration of the Money class. Displays // the result of ((12.50 + 3.75) - 20.00) * 2. import Money; public class DemonstrateMoney2 { public static void main(String[] args) { Money firstValue = new Money(12,50); Money secondValue = new Money(3,75); Money thirdValue = new Money(20,0); // Add 12.50 and 3.75 Money sum = firstValue.add(secondValue); // Subtract 20.00 from the sum Money difference = sum.subtract(thirdValue); // Multiply the difference by 2 Money result = difference.multiply(2); // Display the result System.out.println("((12.50 + 3.75) - 20.00) * 2) is " + result); }
32
Programming and Problem Solving With Java 32 Example: Money Class Same example, but without so many variables // Another demonstration of the Money class. Displays // the result of ((12.50 + 3.75) - 20.00) * 2. Doesn't use any // for literal values or intermediate results. import Money; public class DemonstrateMoney3 { public static void main(String[] args) { // Display ((12.50 + 3.75) - 20.00) * 2 Money result = new Money(12,50).add(new Money(3,75)).subtract(new Money(20,0)).multiply(2); System.out.println("((12.50 + 3.75) - 20.00) * 2) is " + result); }
33
Programming and Problem Solving With Java 33 Example: Money Class Bank balance keeper // This program lets you deposit and withdraw // money from a bank account. It makes sure you don't withdraw // more than the amount of money currently in the bank. // This program demonstrates the use of the Money class. import Money; import Keyboard; public class BankBalance { public static void main(String[] args) throws java.io.IOException { Money balance = new Money(0, 0); char selection; int dollars; int cents; System.out.println("--- Bank Balance Keeper ---"); System.out.println(); selection = Keyboard.readChar("Deposit Withdraw Quit: ", "dwq");
34
Programming and Problem Solving With Java 34 Example: Money Class while (Character.toLowerCase(selection) != 'q') { switch (Character.toLowerCase(selection)) { case 'd': System.out.println("Enter amount to deposit"); dollars = Keyboard.readInt("Dollars: "); cents = Keyboard.readInt("Cents: "); balance = balance.add(new Money(dollars, cents)); break; case 'w': System.out.println("Enter amount to withdraw"); dollars = Keyboard.readInt("Dollars: "); cents = Keyboard.readInt("Cents: "); if (balance.less(new Money(dollars, cents))) { System.out.println("Error: Can't withdraw more than" + " balance"); } else { balance = balance.subtract(new Money(dollars, cents)); } break; default: System.out.println("Error in switch statement"); break; }
35
Programming and Problem Solving With Java 35 Example: Money Class System.out.println("Current balance is " + balance); System.out.println(); selection = Keyboard.readChar("Deposit Withdraw Quit: ", "dwq"); } Example output --- Bank Balance Keeper --- Deposit Withdraw Quit: d Dollars: 75 Cents: 40 Current balance is 75.40 Deposit Withdraw Quit: d Dollars: 20 Cents: 15 Current balance is 95.55 Deposit Withdraw Quit: w Dollars: 100 Cents: 0 Error: Can't withdraw more than balance Current balance is 95.55 Deposit Withdraw Quit: q
36
Programming and Problem Solving With Java 36 Writing Well-designed Classes Well-designed class should look like a type Set of private values Set of public operations on those values Ideal class is Complete : has all necessary operations General : is useful in many applications
37
Programming and Problem Solving With Java 37 Writing Well-designed Classes What not to do: this program requires poorly-designed Money class // This program lets you deposit and withdraw // money from a bank account. It makes sure you don't withdraw // more than the amount of money currently in the bank. // NOTE: This program demonstrates an inappropriate design of // an abstract data type. public class BankBalance { public static void main(String[] args) throws java.io.IOException { Money balance = new Money(0, 0); char selection; System.out.println("--- Bank Balance Keeper ---"); System.out.println(); selection = Keyboard.readChar("Deposit Withdraw Quit: ", "dwq");
38
Programming and Problem Solving With Java 38 Writing Well-designed Classes What not to do (continued) while (Character.toLowerCase(selection) != 'q') { switch (Character.toLowerCase(selection)) { case 'd': balance.add(); break; case 'w': balance.subtract(); break; default: System.out.println("Error in switch statement"); break; } System.out.println("Current balance is " + balance); System.out.println(); selection = Keyboard.readChar("Deposit Withdraw Quit: ", "dwq"); } Poor design here requires poor design of Money class Poor design
39
Programming and Problem Solving With Java 39 Writing Well-designed Classes Base Money class on just this program Program doesn't need getDollars(), getCents(), multiply(), less(), equals(): leave them out of Money class add() method should ask user for input value, add that value to this object subtract() method should ask user for input value, subtract that value from this object only if result >= 0 Problems Incomplete Specific to the application (not general)
40
Programming and Problem Solving With Java 40 Writing Well-designed Classes Changes to the Money class add() method // add: Asks the user to enter an amount to deposit, then adds // what the user enters to the value of this object public void add() throws java.io.IOException { System.out.println("Enter amount to deposit"); int dollars = Keyboard.readInt("Dollars: "); int cents = Keyboard.readInt("Cents: "); setAmount(this.dollars + dollars, this.cents + cents); } add() does more than add Includes asking user for input Not useful in other programs Probably not useful in other parts of this program!
41
Programming and Problem Solving With Java 41 Writing Well-designed Classes Changes to the Money class subtract() method // subtract: Asks the user to enter an amount to withdraw, then // subtracts what the user enters from the value of this // object. Won't let the user subtract more than the // current value of this object public void subtract() throws java.io.IOException { System.out.println("Enter amount to withdraw"); int dollars = Keyboard.readInt("Dollars: "); int cents = Keyboard.readInt("Cents: "); if (this.dollars < dollars || (this.dollars == dollars && cents < cents)) { System.out.println("Error: Can't withdraw more than" + " balance"); } else { setAmount(this.dollars - dollars, this.cents - cents); } Not useful in other programs or other parts of this program!
42
Programming and Problem Solving With Java 42 Writing Well-designed Classes Write a method specification before writing the method Specification includes answers to What will the method do? What is the name of the method? What assumptions does the method make? What information does the method need?
43
Programming and Problem Solving With Java 43 Writing Well-designed Classes Method specification example: Counter.increment() What will the method do? Our method will add one to the counter's value. What is the name of the method? Verb usually makes a good method name "increment" What assumptions does the method make? None for this method What information does the method need? No parameters Descriptive comment: // increment: Adds one to the counter's value
44
Programming and Problem Solving With Java 44 Class Methods and Variables Class (static) vs. instance variables Instance variable: each instance has its own copy Class variable: the class has one copy for all instances Example class Counter { public Counter() { value = 0; numCounters++; }... private int value; private static int numCounters = 0; } Can use instance variables In instance methods only Can use class variables In instance methods In class methods
45
Programming and Problem Solving With Java 45 Class Methods and Variables Class (static) vs. instance methods Instance methods can access instance variables, class variables, instance methods, class methods Class methods can access class variables and methods Uses of class methods Provide access to class variables without using an object class Counter {... public static int getNumCounters() { return numCounters; } }... System.out.println("Number of counters: " + Counter.getNumCounters()); Package a related group of methods (Math, Keyboard) without objects
46
Programming and Problem Solving With Java 46 The Keyboard Class The Keyboard class is group of related methods No object needed to use Keyboard class methods int name = Keyboard.readString("Enter your name: "); int age = Keyboard.readInt("Enter your age: "); Keyboard class outline Need BufferedReader and NumberFormat objects -- both are static public class Keyboard {... private static BufferedReader inputStream = new BufferedReader(new InputStreamReader(System.in)); private static NumberFormat aNumberFormatter = NumberFormat.getInstance(); }
47
Programming and Problem Solving With Java 47 The Keyboard Class The readString() methods readString() with a prompt // readString: Displays the given prompt, then waits for the // user to type a line, then returns all characters // the user typed as a string. public static String readString(String prompt) throws java.io.IOException { System.out.print(prompt); System.out.flush(); return inputStream.readLine(); } readString() with no prompt (calls the other one) // readString: (Final version) Waits for the user to type a line, // then returns all characters the user typed as a // string. public static String readString() throws java.io.IOException { return readString(""); }
48
Programming and Problem Solving With Java 48 The Keyboard Class The readLong() method // readLong: (First version) Displays the given prompt, then waits // for the user to type a number, then returns that // number as a long. public static long readLong(String prompt) throws java.io.IOException, ParseException { System.out.print(prompt); System.out.flush(); return aNumberFormatter.parse(inputStream.readLine()).longValue(); } Doesn't handle non-numeric input Throws ParseException instead (confusing to beginners) Better to ask user to re-enter number Enter a number: 123x Please enter an integer Enter a number: _
49
Programming and Problem Solving With Java 49 The Keyboard Class Catch ParseException error in readLong() method Use try-catch block try part: code that may throw an exception catch part: code for handling the exception, if it occurs Example NumberFormat formatter = NumberFormat.getInstance(); try { System.out.print("Enter a long value: "); System.out.flush(); value = formatter.parse(inputStream.readLine()).longValue(); } catch (ParseException e) { System.out.println("Not a long -- setting to 0"); value = 0; }
50
Programming and Problem Solving With Java 50 The Keyboard Class The readLong() method, handles ParseExceptions // readLong: (Final version) Displays the given prompt, then waits // for the user to type a number, then returns that // number as a long. If the user enters an invalid // response, prompts the user to retype the response. public static long readLong(String prompt) throws java.io.IOException { long value = 0; boolean readAgain; do { try { readAgain = false; value = aNumberFormatter.parse(readString(prompt)).longValue(); } catch (ParseException e) { System.out.println("Please enter an integer"); readAgain = true; } } while (readAgain); return value; } Use readString()
51
Programming and Problem Solving With Java 51 The Keyboard Class The readLong() method for ranges // readLong: Displays the given prompt, then waits for the user // to type a number, then returns that number as a long. // If the user enters an invalid response, prompts the // user to retype the response. If the user types a value // outside the range from lowValue to highValue, prompts // the user to retype the response. // NOTE: Assumes highValue >= lowValue public static long readLong(String prompt, int lowValue, int highValue) throws java.io.IOException { long value = readLong(prompt); while (value highValue) { System.out.println("Please enter an integer between " + lowValue + " and " + highValue); value = readLong(prompt); } return value; } The readLong() method with no parameters // readLong: Waits for the user to type a number, then returns that // number as a long. If the user enters an invalid // response, prompts the user to retype the response. public static long readLong() throws java.io.IOException { return readLong(""); } Use the other readLong()
52
Programming and Problem Solving With Java 52 The Keyboard Class Three versions of readLong No parametersi = readLong(); Prompti = readLong("Value: "); Prompt and rangei = readLong("Value: ", 0, 100); Can use readLong() to write readInt() (3 versions) readShort() (3 versions) readByte() (3 versions) These are all integer types long type has widest range - just narrow it for other types
53
Programming and Problem Solving With Java 53 The Keyboard Class // readInt: Waits for the user type a number, then returns that // number as an int. If the user enters an invalid // response, prompts the user to retype the response. public static int readInt() throws java.io.IOException { return (int) readLong("", Integer.MIN_VALUE, Integer.MAX_VALUE); } // readInt: Displays the given prompt, then waits for the user // to type a number, then returns that number as an int. // If the user enters an invalid response, prompts the // user to retype the response. public static int readInt(String prompt) throws java.io.IOException { return (int) readLong(prompt, Integer.MIN_VALUE, Integer.MAX_VALUE); } // readInt: Displays the given prompt, then waits for the user // to type a number, then returns that number as an int. // If the user enters an invalid response, prompts the // user to retype the response. If the user types a value // outside the range from lowValue to highValue, prompts // the user to retype the response. // NOTE: Assumes highValue >= lowValue public static int readInt(String prompt, int lowValue, int highValue) throws java.io.IOException { return (int) readLong(prompt, lowValue, highValue); }
54
Programming and Problem Solving With Java 54 Class Methods in App. Class Class method can call other class methods without using an object Example (no objects!) import Keyboard; class Test { public static void main(String[] args) throws java.io.IOException { int value = Keyboard.readInt("Enter value: "); System.out.println("You entered " + value); } Can carry this further... All methods in Keyboard class are class methods main is a class method
55
Programming and Problem Solving With Java 55 Class Methods in App. Class Can organize code (without objects) using class methods Example public class DemonstrateClassMethodCalls { public static void firstMethod() { System.out.println("In firstMethod()"); } public static void secondMethod() { System.out.println("In secondMethod() " + "- now calling firstMethod()"); firstMethod(); System.out.println("Back in secondMethod()"); } Output from secondMethod() In secondMethod() - now calling firstMethod() In firstMethod() Back in secondMethod()
56
Programming and Problem Solving With Java 56 Class Methods in App. Class main() is also a class method main() can call other class methods in the application class (the same class as main) Can organize program with methods, but without objects Divide work of methods in application class by purpose Process called stepwise refinement or functional decomposition The primary development technique in non-object-oriented programming languages
57
Programming and Problem Solving With Java 57 Stepwise Refinement
58
Programming and Problem Solving With Java 58 Stepwise Refinement Example: Keep track of person's checking account Divide into subproblems Get new information (checks and deposits) from the user Change existing information Store the information in a file on the hard disk drive Read information from a file Balance the checkbook Each subproblem may be too complex to solve without further planning Keep dividing until each sub-sub-...-subproblem is trivial
59
Programming and Problem Solving With Java 59 Stepwise Refinement Example: divide "Get new information (checks and deposits) from the user" Read the check or deposit number from the user Read the date from the user Read the payee information from the user Read the amount of the check or deposit Read the income or expense category of the check or deposit Store the information Turn each step into a static method // getCheckOrDepositNumber: Returns the check or deposit number // entered by the user static int getCheckOrDepositNumber() throws java.io.IOException { return (Keyboard.readInt("Enter the check or deposit number: ")); }
60
Programming and Problem Solving With Java 60 Stepwise Refinement Result of stepwise refinement: decomposition hierarchy Shows how problem is divided into subproblems
61
Programming and Problem Solving With Java 61 Stepwise Refinement: Use in OO Stepwise refinement different from object-oriented design Stepwise refinement: emphasis on division of tasks Object-oriented design: emphasis on objects and their relationships Can use stepwise refinement in object-oriented design Object-oriented design identifies classes and methods first When methods identified, may want to divide the work of some methods with "helper" methods
62
Programming and Problem Solving With Java 62 Stepwise Refinement: Use in OO Example: program to compute employee pay Start with object-oriented design to get Employee class setName() setHours() setHourlyRate() setPay() getName() getHours() getHourlyRate() getPay() Use stepwise refinement to divide main() by task readEmployeeInfo() computePay() displayPay()
63
Programming and Problem Solving With Java 63 Stepwise Refinement: Use in OO Employee pay program without Employee class // Computes the pay for an employee by multiplying the // hours worked by the rate per hour. This program is an example of // using class methods in the application class to simplify main(). import Employee; import Keyboard; public class EmployeePay { // readEmployeeInfo: Read the employee's information from // the user static void readEmployeeInfo(Employee anEmployee) throws java.io.IOException { anEmployee.setName(Keyboard.readString("Employee name: ")); anEmployee.setHours(Keyboard.readDouble("Hours: ")); anEmployee.setHourlyRate(Keyboard.readDouble("Rate: ")); }
64
Programming and Problem Solving With Java 64 Stepwise Refinement: Use in OO // computePay: Compute the pay, based on the employee's // information static void computePay(Employee anEmployee) { anEmployee.setPay(anEmployee.getHourlyRate() * anEmployee.getHours()); } // displayPay: Display the pay on the screen static void displayPay(Employee anEmployee) { System.out.println("Name: " + anEmployee.getName() + " Pay: " + anEmployee.getPay()); } public static void main(String[] args) { Employee anEmployee = new Employee(); System.out.println("--- Compute Employee Pay Program ---"); readEmployeeInfo(anEmployee); computePay(anEmployee); displayPay(anEmployee); }
65
Programming and Problem Solving With Java 65 Changing Formal Parameters If formal parameter is object Changing object's value changes actual parameter's If formal parameter is primitive Changing parameter's value doesn't affect actual parameter Can use this techique to return values from method Especially useful when method needs to return more than one value Common in non-object-oriented programs (If returning just one value, use return statement)
66
Programming and Problem Solving With Java 66 Changing Formal Parameters // change: Changes the value of anIntFormal and // aMoneyFormal to 0 public static void change(int anIntFormal, Money aMoneyFormal) { anIntFormal = 0; aMoneyFormal.setAmount(0,0); } public static void main(String[] args) { int anIntActual = 123; Money aMoneyActual = new Money(123,45); System.out.println("--- Before method call ---"); System.out.println("anIntActual: " + anIntActual); System.out.println("aMoneyActual: " + aMoneyActual); change(anIntActual, aMoneyActual); System.out.println("--- After method call ---"); System.out.println("anIntActual: " + anIntActual); System.out.println("aMoneyActual: " + aMoneyActual); } --- Before method call --- anIntActual: 123 aMoneyActual: 123.45 --- After method call --- anIntActual: 123 aMoneyActual: 0.00
67
Programming and Problem Solving With Java 67 Quadratic Equation: ax 2 +bx+c=0 Class Methods: Quadratic Eq.
68
Programming and Problem Solving With Java 68 Class Methods: Quadratic Eq. Quadratic equation: ax 2 + bx + c = 0 a, b, c are numbers value of x that makes equation true is root of equation Solution to quadratic equation Example: graph of -2 x 2 + 3 x + 4 = 0
69
Programming and Problem Solving With Java 69 Class Methods: Quadratic Eq. Program to find roots of quadratic equation // Finds roots of a quadratic equation entered by the user. import Keyboard; public class SolveQuadraticEquation { // plusRoot: Returns the "plus" root of a quadratic equation. // Assumes b*b - 4*a*c >= 0 and that a != 0 static double plusRoot(double a, double b, double c) { double numerator, denominator; numerator = b + Math.sqrt(b * b - 4 * a * c); denominator = 2 * a; return numerator / denominator; } // minusRoot: Returns the "minus" root of a quadratic equation. // Assumes b*b - 4*a*c >= 0 and that a != 0 static double minusRoot(double a, double b, double c) { double numerator, denominator; numerator = -b + Math.sqrt(b * b - 4 * a * c); denominator = 2 * a; return numerator / denominator; }
70
Programming and Problem Solving With Java 70 Class Methods: Quadratic Eq. public static void main(String[] args) { System.out.println("--- Solve quadratic equation " + "ax^2 + bx + c = 0 ---"); System.out.println(); double a = Keyboard.readDouble("Enter value of a: "); double b = Keyboard.readDouble("Enter value of b: "); double c = Keyboard.readDouble("Enter value of c: "); System.out.println(); System.out.println("Equation is " + a + "x^2 + " + b + "x + " + c + " = 0"); System.out.println("One root is " + plusRoot(a, b, c)); System.out.println("Another root is " + minusRoot(a, b, c)); } --- Solve quadratic equation ax^2 + bx + c = 0 --- Enter value of a: -2 Enter value of b: 3 Enter value of c: 4 Equation is -2.0x^2 + 3.0x + 4.0 = 0 One root is -0.8507810593582121 Another root is 2.350781059358212
71
Programming and Problem Solving With Java 71 Computer Networks A computer network is A set of computers connected for the purpose of sharing information A computer network consists of Communications media Devices Software
72
Programming and Problem Solving With Java 72 Computer Networks Internet Protocol (IP) Protocol: set of rules that computers follow to communicate with each other Computers on the Internet use IP Internet is packet-switched network Sends information like post office
73
Programming and Problem Solving With Java 73 Computer Networks Packet Works like a postal letter Contains up to about 65,000 bytes (characters) of information Message often consists of many packets Packet header First several bytes of the packet Contains the address of the packet's recipient Computers examine packet header and forward packet to intended recipient No dedicated physical connection between source of packet and its intended recipient
74
Programming and Problem Solving With Java 74 Computer Networks Circuit-switching network Used in some computer networks Works like the telephone network -- dedicated physical connection between computers
75
Programming and Problem Solving With Java 75 Computer Networks IP makes sure packets arrive correctly But that’s all it does Transmission Control Protocol (TCP) Breaks messages into packets before sending Reassembles packets into messages at receiver Rearrange order of received packets, if necessary Disposes of duplicate packets, when necessary TCP/IP: the combination of TCP and IP
76
Programming and Problem Solving With Java 76 Computer Networks Internet Addresses Each computer on the Internet has a unique address Address is a 32-bit number consisting of four 8-bit bytes (each between 0 and 255) Example: ACM’s address is 199.222.69.10 Address is hierarchical First byte: which of 256 large networks Last byte: a particular computer on a network Current scheme running out of numbers Scheduled for replacement with 128-bit numbering
77
Programming and Problem Solving With Java 77 Computer Networks Domain Name System (DNS) Numbered addresses convenient for computers But, inconvenient for people DNS allows users to use mnemonic names: www.acm.org instead of 199.222.69.10 DNS translates the mnemonic names into numbered addresses DNS is a distributed database User uses mnemonic name Network consults the closest DNS table on the Internet to translate the name to a number
78
Programming and Problem Solving With Java 78 Computer Networks DNS names hierarchical But from right to left Right-most part of the name is the top-level domain Common top-level domains
79
Programming and Problem Solving With Java 79 Computer Networks The World Wide Web Very large, distributed collection of linked documents accessible by a Web browser Web documents use Hypertext Markup Language (HTML) HTML Includes regular text, formatting tags, and links to other documents. Uses Uniform Resource Locators (URLs) to specify documents
80
Programming and Problem Solving With Java 80 Computer Networks URLs Use default port, specific directory protocol://hostname/location/ Use default port, specific file protocol://hostname/location Use specific port, specific directory protocol://hostname:port/location/ Use specific port, specific file protocol://hostname:port/location Example URL http://www.acm.org/index.html Protocols http (Hypertext Transmission Protocol) ftp (File Transfer Protocol) mailto -- for sending mail messages telnet -- for using another computer remotely.
81
Programming and Problem Solving With Java 81 Networks: Java Programming Network programming in Java is relatively simple java.net package has lots of net functionality java.net.URL class For storing URLs, like a File object stores file information Example URL acmURL = new URL("http://www.acm.org"); Methods
82
Programming and Problem Solving With Java 82 Networks: Java Programming Example of URL class // Demonstrates the methods in the URL class import Keyboard; import java.net.*; class DemonstrateURL { public static void main(String[] args) throws java.net.MalformedURLException, java.io.IOException { System.out.println("--- URL Demonstration ---"); do { System.out.println(); // Get the URL name from the user, make URL object URL loc = new URL(Keyboard.readString("Enter URL: ")); // Display information about the URL System.out.println("Protocol is " + loc.getProtocol()); System.out.println("Port is " + loc.getPort()); System.out.println("Host is " + loc.getHost()); System.out.println("File is " + loc.getFile()); } while (Keyboard.readChar("Another (y/n): ", "yn") == 'y'); }
83
Programming and Problem Solving With Java 83 Networks: Java Programming Sample run Enter URL: http://www.acm.org Protocol is http Port is -1 Host is www.acm.org File is / Another (y/n): y Enter URL: ftp://www.acm.org:9999/myfile.txt Protocol is ftp Port is 9999 Host is www.acm.org File is /myfile.txt Another (y/n): y Enter URL: http://www.bogus.bogus/bogus/bogus.txt Protocol is http Port is -1 Host is www.bogus.bogus File is /bogus/bogus.txt Another (y/n): n
84
Programming and Problem Solving With Java 84 Networks: Java Programming Simple way to get content of URL URL.openStream() gives InputStream object connected to content Use just about like System.in Wrap InputStream object in BufferedReader, then use BufferedReader.readline()
85
Programming and Problem Solving With Java 85 Networks: Java Programming Example of URL.openStream() // This program displays the contents of a URL on the screen import Keyboard; import java.net.*; import java.io.*; // Need this for BufferedReader class DisplayURLFile { public static void main(String[] args) throws java.net.MalformedURLException, java.io.IOException { System.out.println("--- URL Content Retriever ---"); System.out.println(); // Get the URL name from the user, make URL object URL loc = new URL(Keyboard.readString("Enter URL: ")); // Make a BufferedReader object, connect to URL BufferedReader input = new BufferedReader(new InputStreamReader(loc.openStream())); System.out.println("--- Content Follows ---"); System.out.println(); // Read and display all lines from URL String line = input.readLine(); while (line != null) { System.out.println(line); line = input.readLine(); }
86
Programming and Problem Solving With Java 86 Networks: Java Programming Sample run --- URL Content Retriever --- Enter URL: http://www.acm.org --- Content Follows --- ACM Brings You the World of Computing (Rest of HTML document appears here)
87
Programming and Problem Solving With Java 87 Networks: Java Programming Sockets Allow two-way communication between computers (URL class allows commication in one direction only) Socket: connection to a port on another computer Ports Port specifies communication line into a computer First 1024 port numbers usually reserved for system use Default port numbers between 0 to 1023 http server: port 80 ftp server: port 21 For two-way communication, each computer should create socket connected to same port number
88
Programming and Problem Solving With Java 88 Networks: Java Programming Socket programming Server: computer that listens for connections Client: requests connection from the server How to write a server program Make server listen ServerSocket myServerSocket = new ServerSocket(PORT_NUMBER); It hears request Socket mySocket = myServerSocket.accept(); Create input or output streams (or both) to client BufferedReader input = new BufferedReader(new InputStreamReader( mySocket.getInputStream())); Can read from client just like any other stream Close everything when done input.close(); mySocket.close(); myServerSocket.close();
89
Programming and Problem Solving With Java 89 Networks: Java Programming Example server program // A short demonstration of how to set up a server // process on a socket, then send listen for information sent // through the socket to this server process import java.net.*; import java.io.*; public class Server { static final int PORT_NUMBER = 9999; public static void main(String[] args) throws java.io.IOException { System.out.println("--- Server Process ---"); System.out.println(); ServerSocket myServerSocket = new ServerSocket(PORT_NUMBER); System.out.println("Ready for client connection..."); // Wait for the client to start communication Socket mySocket = myServerSocket.accept(); System.out.println("Client connected..."); System.out.println();
90
Programming and Problem Solving With Java 90 Networks: Java Programming Example server program (continued) // Make a BufferedReader object, connect to socket BufferedReader input = new BufferedReader(new InputStreamReader( mySocket.getInputStream())); // Read and display all lines from socket System.out.println("Messages from client:"); String line = input.readLine(); while (line != null) { System.out.println(">> " + line); line = input.readLine(); } input.close(); mySocket.close(); myServerSocket.close(); }
91
Programming and Problem Solving With Java 91 Networks: Java Programming How to write a client program Request connection from server Socket mySocket = new Socket("www.myHost.edu", 1234); Create input or output stream (or both) to server PrintWriter output = new PrintWriter(new OutputStreamWriter( mySocket.getOutputStream()), true); Send information to server with print() or println() Close everything when done output.close(); mySocket.close(); tells object to flush stream after every println()
92
Programming and Problem Solving With Java 92 Networks: Java Programming Example client program // A short demonstration of how to connect a client // socket, then send information through the socket to the // server import Keyboard; import java.net.*; import java.io.*; public class Client { static final int PORT_NUMBER = 9999; public static void main(String[] args) throws java.io.IOException { // Display program title System.out.println("--- Client Process ---"); System.out.println(); // Get host address from user, connect socket to that // host at PORT_NUMBER Socket mySocket = new Socket(Keyboard.readString("Host: "), PORT_NUMBER); Note: same port number as server!
93
Programming and Problem Solving With Java 93 Networks: Java Programming Example client program (continued) // Make an output stream, connect to the socket PrintWriter output = new PrintWriter(new OutputStreamWriter( mySocket.getOutputStream()), true); System.out.println("Connected to server..."); // Send some information to server String message = Keyboard.readString("Message to send: "); while (message != "") { output.println(message); message = Keyboard.readString("Message to send: "); } // Close the output stream and the socket output.close(); mySocket.close(); }
94
Programming and Problem Solving With Java 94 Networks: Java Programming Sample run of server and client programs Server (Unix machine) % java Server --- Server Process --- Ready for client connection... Client connected... Messages from client: >> I am typing this message on the client >> machine, and it will show up on the >> server. % Client (Windows 95 machine) C:\> java Client --- Client Process --- Host: myserver Connected to server... Message to send: I am typing this message on the client Message to send: machine, and it will show up on the Message to send: server. Message to send: C:\>
95
Programming and Problem Solving With Java 95 Communications Media Twisted pair wiring Similar to phone wire May be shielded -- protects from electromagnetic interference Inexpensive, but slow Coaxial cable (coax) Similar to cable TV wire Consists of wire surrounded by dielectric (insulation) Medium expense and speed Fiber optic cable Consists of glass strands Transmits light, not electricity No electromagnetic interference Most expensive, fastest
96
Programming and Problem Solving With Java 96 Communications Media Can transmit signals via radio Microwaves are a popular approach Line-of-signt transmission
97
Programming and Problem Solving With Java 97 Communications Media Satellites can transmit much farther than microwaves
98
Programming and Problem Solving With Java 98 Communications Media Other wireless transmission Conventional radio Cellular telephones
99
Programming and Problem Solving With Java 99 Network Topology Topology Layout or organization of network connections Most common topologies Ring Star Bus
100
Programming and Problem Solving With Java 100 Network Topology Ring topology (token ring) Computers linked in a circle Token constantly traveling around the ring Token travels in only one direction Computer must wait until it reads the token before it can send a message to another computer When a computer reads the token, can append message to end of messages following the token
101
Programming and Problem Solving With Java 101 Network Topology Star topology Requires a central computer (server) Central computer acts as the hub for all network communication To send a message, computer sends packet to server, which routes message to destination To read a message, computer waits for packets from the server
102
Programming and Problem Solving With Java 102 Network Topology Bus topology Most common topology today Each computer connected to the bus (a cable) To send a message, computer broadcasts packet on the bus To read a message from the network, computer monitors all broadcast messages for any packets with its identifier
Similar presentations
© 2024 SlidePlayer.com Inc.
All rights reserved.