cs303euser defined methods1 cs 303e class 7 part 1: designing complex programs the sooner you start...

51
CS303E User Defined Methods 1 CS 303E Class 7 Part 1: Designing Complex Programs The sooner you start to code, the longer your program will take. -Roy Carlson, U Wisconsin

Upload: wesley-day

Post on 13-Dec-2015

213 views

Category:

Documents


0 download

TRANSCRIPT

CS303E User Defined Methods 1

CS 303E Class 7 Part 1:

Designing Complex Programs

The sooner you start to code, the longer your program will take.-Roy Carlson, U Wisconsin

CS303E User Defined Methods 2

Tally Grades(pp. 96–110)

Request: A program to tally grades on a test.

Analysis (details of input and output):Input: scores on a test.Output: Number of As, Bs, Cs, Ds, Fs (tallies) and

running average.

Interface: Fields, buttons, etc. needed for I/O.Fields and labels for input (score) and outputs

(tallies and average).Buttons to tally another score and to reset all.

CS303E User Defined Methods 3

Design — Variables

Window components.

Global variables:Needed? Yes:

Click Tally button for each score — “user loop”.

Tallies, average, other variables must retain their values between button clicks.

Global variables: tallyA, tallyB, …, tallyF, numberOfTests, totalOfTests, average.

CS303E User Defined Methods 4

Method buttonClicked

Determines which button was clicked and calls the appropriate method:

buttonClicked

if (reset button clicked)

resetGlobalVariables ();

else

processScore ();

set focus to score input field;

CS303E User Defined Methods 5

Method resetGlobalVariables

resetGlobalVariablesset tallies to 0; // tallyA, …set totals to 0; // totalOfTests, …set average to 0;display 0 in score field;displayTalliesAndAverage ();

Method call for last action because it will be needed again when processing scores.

CS303E User Defined Methods 6

Method displayTalliesAndAverage

displayTalliesAndAverage

display the tallies and average on the screen;

Computation done in global variables, but display done in fields or other window components.

CS303E User Defined Methods 7

Method processScoreprocessScore

if (score is invalid)display error message;

else{ get score value from field;

if (score < 0 or score > 100)display error message;

else{ updateTallies (score);

updateAverage (score); displayTalliesAndAverage ();

}}

Separate methods for computations of a few lines or more.

CS303E User Defined Methods 8

Update Methods

updateTallies (int score);update the proper tally for score;

updateAverage (score);update the totals for score;compute the average;

Simple enough that pseudocode isn’t needed.

CS303E User Defined Methods 9

Coding — Step 1 (pp. 99–101)

Code:• the import, class, and method main.• all the window objects — labels, fields, and

buttons declared.• method buttonClicked.

Omit global variables — not needed yet.

Stub out the methods buttonClicked calls.

Run and debug.• What should you see?

CS303E User Defined Methods 10

Coding — Step 2( pp. 100-101)

Code the methods called by buttonClicked.

Add global variables — needed now.

Stub out the methods called by methods added above.

Run and debug.• What should you see?

CS303E User Defined Methods 11

Coding — Step 3(pp. 101-104)

Code the rest of the methods, removing all stubs.

Run and debug.• What should you see?

CS303E User Defined Methods 12

Preconditions and Postconditions

Preconditions:Statement of what must be true before a method

can be invoked — inputs required in parameters or globals.

Postconditions:Statement of what the method will guarantee to

be true after it is executed if the preconditions are met — values computed and returned or changed, errors detected.

CS303E User Defined Methods 13

Example

Text pp. 94-96:

// Preconditions: number is an integer >= 0.

// Postconditions: The number of divisors in

// number is returned.

private int computeCount (int number)

{ . . . ;

return count;

}

CS303E User Defined Methods 14

Call Stack — Run-time Errors

Exception occurred during event dispatching:java.lang.ArithmeticException: / by zero at TallyGrades.updateAverage(TallyGrades.java) at TallyGrades.processScore(TallyGrades.java) at TallyGrades.buttonClicked(TallyGrades.java) at BreezyGUI.GBFrameButtonListener.actionPerformed

(GBFrame.java:241)

at java.awt.Button.processEvent(Button.java:281) at . . .

Press Enter to continue

CS303E User Defined Methods 15

CS 303E Class 7 Part 2

Characters, Strings, and the Math class

"The time has come, "the Walrus said, "To talk of many things: of shoes - and ships - and sealing wax - of cabbages - and kings - And why the sea is boiling hot - And whether pigs have wings." - Lewis Carroll, 1871, in Through the Lookinglass.

CS303E User Defined Methods 16

Primitive Data Types

Numeric types:

int, double, and others

Character type:

char

Boolean type.

CS303E User Defined Methods 17

Characters — type char

Type char represents the 64,768 characters (2 bytes) in the Unicode system.

The ASCII character set (representing English keyboard characters) is shown in Appendix D.

Char constants use single quotes: 'A'.

CS303E User Defined Methods 18

Wrapper Classes and Objects

pages 371 - 373 in text All primitive data types have a class associated

with various methods. These wrapper objects can also store one

primitive data type value for each object. The usefulness of this is described later.

The wrapper class for a char is the Character class.

CS303E User Defined Methods 19

Character Operations

char letter = 'a', digit = '4';

System.out.println (Character.isLetter (letter));

System.out.println (Character.digit (digit, 10));

System.out.println (Character.digit (letter, 16));

int i = letter;

System.out.println(i);

Note: Character char

CS303E User Defined Methods 20

Type Conversions

Each character value maps to an integer. For the ASCII character set, these numbers

range from 0 to 127. Use (char) i to get a character value from

an int. Use (int) ch to get the ASCII value from a char.

examples of casting.

CS303E User Defined Methods 21

Casting for ints

• Java will not assign a value of a more inclusive type to a variable of a less inclusive type unless the code explicitly converts the type.

• Each primitive type can be cast to any other primitive type, but information may be lost.

int i = 5;double d = 3.5;i = (int) d; // Cast operationSystem.out.println (i); // Displays 3

(int) truncates by dropping the fractional part.

CS303E User Defined Methods 22

Strings (page 126)

String str = "Hey Joe!";

System.out.println (str.length());

System.out.println (str.charAt(4));

System.out.println (str.indexOf('J'));

System.out.println (str.toUpperCase());

A string is an array of chars:

'H' 'e' 'y' ' ' 'J' 'o' 'e' '!'

0 1 2 3 4 5 6 7

CS303E User Defined Methods 23

Standard String Processing Loop

for (int i = 0; i < str.length(); i++){ char ch = str.charAt(i); <process ch>}

'H' 'e' 'y' ' ' 'J' 'o' 'e' '!'

0 1 2 3 4 5 6 7

CS303E User Defined Methods 24

Defining a String Method

Write a method that tests a String to see whether or not it represents an integer. A String represents an integer if it is not empty and contains just decimal digits.

// Input parameter: a String// Returns: true if the String is not empty and// contains just digits or false otherwise

boolean validInt (String str){ . . .}

CS303E User Defined Methods 25

Defining a String Method

// Input parameter: a String// Returns: true if the String is not empty and// contains just digits or false otherwise.

public boolean validInt (String str){ if (str.equals("")) return false; // Empty for (int i = 0; i < str.length(); i++) { char ch = str.charAt(i); if (! Character.isDigit(ch)) // Not digit return false; } return true; // Got through}

CS303E User Defined Methods 26

Equality

Use == and != with primitive types and window objects.

Use equals and ! … equals with all other types, such as String.

String a = "xyz", b = "xyz";

if (a == b) ... // Always false

if (a.equals(b)) ... // Use this instead

CS303E User Defined Methods 27

Lexicographical Order

"Ann" < "Bill" < "bill" // Good idea, bad Java

String str1 = "Ann", str2 = "Bill";

str1.compareTo("Ann"); // Returns 0

str1.compareTo(str2) // Returns int < 0

str2.compareTo(str1) // Returns int > 0

if (str1.compareTo(str2) < 0) // str1 comes before str2

CS303E User Defined Methods 28

Palindrome, pp. 129–130 — Example of String processing

public void buttonClicked (Button buttonObj){ String aString = stringField.getText(); aString = aString.toUpperCase(); if (isPalindrome (aString)) messageBox ("Yes, you entered a palindrome."); else messageBox ("No, you did not enter a palindrome.");}

private boolean isPalindrome (String s){ int lastPosition = s.length() - 1; int middlePosition = lastPosition / 2; int forward = 0; int backward = lastPosition; while (forward <= middlePosition){ if (s.charAt (forward) != s.charAt (backward)) return false; forward++; backward--; } return true;}

CS303E User Defined Methods 29

The Math Class(pp. 134–135)

Contains several useful methods and constants:abs (number) Returns the absolute value of number.sqrt (number) Returns the square root of number.

pow (x, y) Returns xy (all double).PI Constant — double value closest to .

double side = . . .;

double area = Math.sqrt (side);

Use the class name Math before the method name.

CS303E User Defined Methods 30

Rounding

Math.round rounds to the nearest whole number, as a long.

int i = 5;double d = 3.5;

i = (int) Math.round (d); // Round operationSystem.out.println (i); // Displays 4

CS303E User Defined Methods 31

Random NumbersProblem: Generate a random integer between 1 and 6 for rolling dice.

Math.random() // Returns a double, d, where 0 <= d < 1

Math.random() * 6 // Returns a double, d, where 0 <= d < 6

(int) (Math.random() * 6) // Returns an int, i, where 0 <= i <= 5

(int) (Math.random() * 6) + 1 // Returns an int, i, where 1 <= i <= 6

CS303E User Defined Methods 32

Floating point arithmetic

Limited precision:float a = 1;

float b = 100000000; // 100,000,000

float c, d, e;

c = b + 5; // Yields 100,000,008

d = b + (a+a+a+a+a); // Yields 100,000,008

d = b + a+a+a+a+a; // Yields 100,000,000

Less problem with double than float.

CS303E User Defined Methods 33

CS 303E Class 7 Part 3: Data Structures I:

Objects and Classes"I have a cat named Trash. In the current politicalclimate it would seem that if I were trying to sell him (at least to a Computer Scientist), I would not stress that he is gentle to humans and is self-sufficient, living mostly on field mice. Rather, I would argue that he is object-oriented."- Roger King

CS303E User Defined Methods 34

What Is a Data Structure?

A data structure is a construct that collects several data items together to be treated as a unit.

Examples:• a string (a collection of characters)• a bank account (a name, ID, and balance)

CS303E User Defined Methods 35

What is an Object?

An object is a data structure that collects information describing some thing so that a program can manipulate it — a collection of data that can be treated as a unit.

Examples:• a person (name, ID, address, phone number, etc.)• a bank account (name, ID, balance, etc.)• a window (labels, fields, text areas, buttons, etc.)

CS303E User Defined Methods 36

An Object Contains its own Data

Each object has a separate area in memory and has space for a value for each datum.

E.g., each object of type Person might have space for the following data:

name:

ID:

address:

phoneNumber:

int

Strings

CS303E User Defined Methods 37

What Is a Class?

A class is a specifcation of —• the data needed in objects of the class type, and• methods for manipulating those objects.

That is, a class is a set of related methods and data.

Examples of classes:• BreezyGUI classes Label, IntegerField,

DoubleField, Button, etc.• String and Math classes

CS303E User Defined Methods 38

Example — Class DoubleField

Specifies —• all the data needed for an object (window

component) of type DoubleField such as the component’s location and extent, its initial value, the characters it contains, etc., and

• the methods for manipulating objects of type DoubleField, such as addDoubleField, getNumber, setNumber, setPrecision, etc.

CS303E User Defined Methods 39

Classes and Objects

A class defines the methods and a template for the data for a set of objects.

An object is an instance of a class.

E.g.:

DoubleField

balance transaction interestRate

Class:

Objects:

CS303E User Defined Methods 40

Software Design with Classes

Like methods, classes are a convenient tool for structuring code — collecting of data (objects) and related methods.

Classes are often useful when we need data structures in a program.

A large system consists of several interacting classes.

CS303E User Defined Methods 41

Clients and Servers

Code that uses a class is also called a client.

Code that implements a class is also called a server.

To the client, the class provides an abstract data type (ADT), which is a black box that hides information about the details of the class from the client and provides only an interface to objects of the class type.

CS303E User Defined Methods 42

One File per Class

Java requires a separate file for each class.

Your code will have: A file with code that defines a class. A separate file for code that uses the class. It

will create objects and manipulate them using methods in the class.

CS303E User Defined Methods 43

Example — Class Student(pp. 159–180)

Analysis (design):

What attributes (data) and behavior (methods) are needed by users for each object in the class (each student)?

Attributes (data) (p. 159):• student name (type String) and• three test scores (each of type int).

CS303E User Defined Methods 44

Declaring class Student and data

public class Student extends Object{ // Instance variables // Each Student object will have a // name and three test scores: private String name; private int test1; private int test2; private int test3;

CS303E User Defined Methods 45

Declaring the class and data

public class ClassName extends Object{ // Declare Fields or Instance variables: private type name1; private type name2, name3; // etc.

CS303E User Defined Methods 46

An Object of type Student

Each object of type Student occupies a separate area in memory and has space for a value for each instance variable:

name:

test1:

test2:

test3:

a String

3 ints

CS303E User Defined Methods 47

Instantiation —Creating an object of a class

typeCode like the following goes in a program to use a class to create objects of the class type:

String sentence = "A sentence fragment.";

Frame frm = new AccountManager();

george = new Student();

CS303E User Defined Methods 48

Class Student - Behavior

What can be done with a Student object from the client’s perspective?• instantiation -- create an object of type Student• set the name and the test scores• get the name and the test scores• get the student’s average, highest score, lowest

score, etc.

CS303E User Defined Methods 49

Methods - Constructors

Constructor methods create or instantiate objects:

// Constructor method // Initialize a new student's name to the

empty // string and his test scores to zero: public Student() { name = ""; test1 = 0; test2 = 0; test3 = 0; }

CS303E User Defined Methods 50

Design the method’s interface.E.g.:

setName (aString) -- returns void

getName () -- returns String

These are object methods -- the object is implied and supplied before the method name with a dot. Calls:Student stu;stu.setName ("Bill Jones");String stuName = stu.getName();

CS303E User Defined Methods 51

Implement the Method // Set a student's name

public void setName (String nm)

{ name = nm;

}

// Get a student's name

public String getName ()

return name;

}