Chapter 7 Writing Your Own Classes

Slides:



Advertisements
Similar presentations
Computer Networks and the Internet CMPT 109 Montclair State University.
Advertisements

1 Java Networking – Part I CS , Spring 2008/9.
28-Jun-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
15-Jul-15 Basic Protocols. 2 Sockets Sockets, or ports, are a very low level software construct that allows computers to talk to one another When you.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
INTRODUCTION TO WEB DATABASE PROGRAMMING
Chapter 2 The Infrastructure. Copyright © 2003, Addison Wesley Understand the structure & elements As a business student, it is important that you understand.
Chapter 5 Networks Communicating and Sharing Resources
Programming and Problem Solving With Java Copyright 1999, James M. Slack Chapter 7 Writing Your Own Classes Writing New Classes Parameters Example: A Money.
TCP/IP protocols Communication over Internet is mostly TCP/IP (Transmission Control Protocol over Internet Protocol) TCP/IP "stack" is software which allows.
Java: Chapter 1 Computer Systems Computer Programming II.
© 2007 Cisco Systems, Inc. All rights reserved.Cisco Public 1 Version 4.0 Network Services Networking for Home and Small Businesses – Chapter 6.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
The Java Programming Language
1 The Internet and Networked Multimedia. 2 Layering  Internet protocols are designed to work in layers, with each layer building on the facilities provided.
RGEC MEERUT(IWT CS703) 1 Java Networking RGEC Meerut.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 3-1.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
5-Dec-15 Sequential Files and Streams. 2 File Handling. File Concept.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
15-1 Networking Computer network A collection of computing devices that are connected in various ways in order to communicate and share resources Usually,
Prepared by: Dr. Abdallah Mohamed, AOU-KW Unit9: Internet programming 1.
1 Chapter 1 INTRODUCTION TO WEB. 2 Objectives In this chapter, you will: Become familiar with the architecture of the World Wide Web Learn about communication.
CompSci 230 S Programming Techniques
Chapter Objectives In this chapter, you will learn:
Information and Computer Sciences University of Hawaii, Manoa
More About Objects and Methods
User-Written Functions
Chapter 2 Basic Computation
Chapter 7 User-Defined Methods.
Chapter 4 Computer Networks – Part 2
WWW and HTTP King Fahd University of Petroleum & Minerals
Objectives You should be able to describe: Interactive Keyboard Input
Yanal Alahmad Java Workshop Yanal Alahmad
University of Central Florida COP 3330 Object Oriented Programming
MCA – 405 Elective –I (A) Java Programming & Technology
Copyright © 2006 Pearson Addison-Wesley. All rights reserved.
Web Design Introduction to the Internet Week One
Lecture 6: TCP/IP Networking By: Adal Alashban
I/O Basics.
Ken Gunnells, Ph.D. - Networking Paul Crigler - Programming
HTTP: the hypertext transfer protocol
How Data Flows through the Internet
Computer Networks.
CS222 Web Programming Course Outline
Copyright © 2006 Pearson Addison-Wesley. All rights reserved.
Clients and Servers 19-Nov-18.
Chapter 3 Introduction to Classes, Objects Methods and Strings
Application layer Lecture 7.
Introduction to Computer Administration
Basic Protocols 24-Nov-18.
Web Design & Development
Copyright © 2006 Pearson Addison-Wesley. All rights reserved.
Clients and Servers 1-Dec-18.
Chapter 1: Computer Systems
Introduction to Computer Concept
TCP/IP Protocol Suite: Review
Basic Protocols 19-Feb-19.
Focus of the Course Object-Oriented Software Development
Unit 3: Variables in Java
Chap 2. Identifiers, Keywords, and Types
Clients and Servers 19-Jul-19.
Clients and Servers 13-Sep-19.
Exceptions and networking
Presentation transcript:

Chapter 7 Writing Your Own Classes Writing New Classes Parameters Example: A Money Class Writing Well-Designed Classes Class Methods and Variables Computer Networks

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); Programming and Problem Solving With Java

Writing New Classes Existing New Class Class 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 Existing Class New Class Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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() Programming and Problem Solving With Java

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 Method call Operations Object internals Programming and Problem Solving With Java

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; Programming and Problem Solving With Java

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); Programming and Problem Solving With Java

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 Method signature // increment: Adds one to the // counter's value public void increment() { value++; } Programming and Problem Solving With Java

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(); Programming and Problem Solving With Java

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(); Programming and Problem Solving With Java

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 Automatic conversion to String: Counter has a toString() method Programming and Problem Solving With Java

Writing New Classes: 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 Programming and Problem Solving With Java

Parameters Can send information to a method Parameter Actual parameter 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 Programming and Problem Solving With Java

Parameters Actual parameter Formal parameter Value 123 passed 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() Programming and Problem Solving With Java

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() Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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(); Programming and Problem Solving With Java

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; ... Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

Example: Money Class Want result to be like "Money calculator" User uses operations, not internals Programming and Problem Solving With Java

Example: Money Class $$$ Example of Money class use Shorter version // 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)); $$$ Programming and Problem Solving With Java

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(); Programming and Problem Solving With Java

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; Programming and Problem Solving With Java

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)); Programming and Problem Solving With Java

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()); $ Programming and Problem Solving With Java

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 && cents > 0) dollars++; cents = cents - 100; // Instance variables private int dollars; private int cents; $$ Programming and Problem Solving With Java

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); } Programming and Problem Solving With Java

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); } Programming and Problem Solving With Java

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"); Programming and Problem Solving With Java

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"); 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)); default: System.out.println("Error in switch statement"); Programming and Problem Solving With Java

Example: Money Class Example output 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 Dollars: 20 Cents: 15 Current balance is 95.55 Deposit Withdraw Quit: w Dollars: 100 Cents: 0 Error: Can't withdraw more than balance Deposit Withdraw Quit: q Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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"); Programming and Problem Solving With Java

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(); default: System.out.println("Error in switch statement"); } 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 Programming and Problem Solving With Java

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) Programming and Problem Solving With Java

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! Programming and Problem Solving With Java

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! Programming and Problem Solving With Java

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? Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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(); } Programming and Problem Solving With Java

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() return readString(""); Programming and Problem Solving With Java

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: _ Programming and Problem Solving With Java

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; Programming and Problem Solving With Java

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() Programming and Problem Solving With Java

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 < lowValue || 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() return readLong(""); Use the other readLong() Programming and Problem Solving With Java

The Keyboard Class Three versions of readLong No parameters i = readLong(); Prompt i = readLong("Value: "); Prompt and range i = 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 Programming and Problem Solving With Java

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) return (int) readLong(prompt, Integer.MIN_VALUE, Integer.MAX_VALUE); // 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) return (int) readLong(prompt, lowValue, highValue); Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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() Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

Stepwise Refinement Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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: ")); } Programming and Problem Solving With Java

Stepwise Refinement Result of stepwise refinement: decomposition hierarchy Shows how problem is divided into subproblems Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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() Programming and Problem Solving With Java

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: ")); } Programming and Problem Solving With Java

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); Programming and Problem Solving With Java

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) Programming and Problem Solving With Java

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 ---"); --- Before method call --- anIntActual: 123 aMoneyActual: 123.45 --- After method call --- aMoneyActual: 0.00 Programming and Problem Solving With Java

Class Methods: Quadratic Eq. Quadratic Equation: ax2+bx+c=0 Programming and Problem Solving With Java

Class Methods: Quadratic Eq. Quadratic equation: ax2 + 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 -2x2 + 3x + 4 = 0 Programming and Problem Solving With Java

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) numerator = -b + Math.sqrt(b * b - 4 * a * c); Programming and Problem Solving With Java

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("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 Programming and Problem Solving With Java

Computer Networks A computer network is A computer network consists of A set of computers connected for the purpose of sharing information A computer network consists of Communications media Devices Software Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

Computer Networks Packet Packet header 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 Programming and Problem Solving With Java

Computer Networks Circuit-switching network Used in some computer networks Works like the telephone network -- dedicated physical connection between computers Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

Computer Networks Internet Addresses Address is hierarchical 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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

Computer Networks DNS names hierarchical Common top-level domains But from right to left Right-most part of the name is the top-level domain Common top-level domains Programming and Problem Solving With Java

Computer Networks The World Wide Web HTML 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 Programming and Problem Solving With Java

Computer Networks URLs Example URL Protocols 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. Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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'); } Programming and Problem Solving With Java

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 File is /myfile.txt Enter URL: http://www.bogus.bogus/bogus/bogus.txt Host is www.bogus.bogus File is /bogus/bogus.txt Another (y/n): n Programming and Problem Solving With Java

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() Programming and Problem Solving With Java

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 ---"); // Read and display all lines from URL String line = input.readLine(); while (line != null) System.out.println(line); line = input.readLine(); } Programming and Problem Solving With Java

Networks: Java Programming Sample run --- URL Content Retriever --- Enter URL: http://www.acm.org --- Content Follows --- <HTML> <HEAD> <TITLE>ACM Brings You the World of Computing</TITLE> (Rest of HTML document appears here) <!-- end bottom spacer and copyright line --> </BODY> </HTML> Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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(); Programming and Problem Solving With Java

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..."); Programming and Problem Solving With Java

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(); Programming and Problem Solving With Java

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() Programming and Problem Solving With Java

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! Programming and Problem Solving With Java

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(); Programming and Problem Solving With Java

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:\> Programming and Problem Solving With Java

Communications Media Twisted pair wiring Coaxial cable (coax) 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 Programming and Problem Solving With Java

Communications Media Can transmit signals via radio Microwaves are a popular approach Line-of-signt transmission Programming and Problem Solving With Java

Communications Media Satellites can transmit much farther than microwaves Programming and Problem Solving With Java

Communications Media Other wireless transmission Conventional radio Cellular telephones Programming and Problem Solving With Java

Network Topology Topology Most common topologies Layout or organization of network connections Most common topologies Ring Star Bus Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java

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 Programming and Problem Solving With Java