CS 303E Class 7 Part 1: Designing Complex Programs - PowerPoint PPT Presentation

About This Presentation
Title:

CS 303E Class 7 Part 1: Designing Complex Programs

Description:

display 0 in score field; displayTalliesAndAverage ... self-sufficient, living mostly on field mice. Rather, I would argue that he is object-oriented. ... – PowerPoint PPT presentation

Number of Views:54
Avg rating:3.0/5.0
Slides: 52
Provided by: MikeS2
Category:

less

Transcript and Presenter's Notes

Title: CS 303E Class 7 Part 1: Designing Complex Programs


1
CS 303E Class 7 Part 1Designing Complex
Programs
The sooner you start to code, the longer your
program will take.-Roy Carlson, U Wisconsin
2
Tally Grades(pp. 96110)
  • 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.

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.

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

5
Method resetGlobalVariables
  • resetGlobalVariables
  • set 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.

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.

7
Method processScore
  • processScore
  • if (score is invalid)
  • display error message
  • else
  • get score value from field
  • if (score lt 0 or score gt 100)
  • display error message
  • else
  • updateTallies (score)
  • updateAverage (score)
  • displayTalliesAndAverage ()
  • Separate methods for computations of a few lines
    or more.

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 isnt needed.

9
Coding Step 1 (pp. 99101)
  • 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?

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?

11
Coding Step 3(pp. 101-104)
  • Code the rest of the methods, removing all stubs.
  • Run and debug.
  • What should you see?

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.

13
Example
  • Text pp. 94-96
  • // Preconditions number is an integer gt 0.
  • // Postconditions The number of divisors in
  • // number is returned.
  • private int computeCount (int number)
  • . . .
  • return count

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.actionPerform
    ed
  • (GBFrame.java241)
  • at java.awt.Button.processEvent(Button.java281)
  • at . . .
  • Press Enter to continue

15
CS 303E Class 7 Part 2Characters, 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.
16
Primitive Data Types
  • Numeric types
  • int, double, and others
  • Character type
  • char
  • Boolean type.

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'.

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.

19
Character Operations
char letter 'a', digit '4' System.out.printl
n (Character.isLetter (letter)) System.out.print
ln (Character.digit (digit, 10)) System.out.prin
tln (Character.digit (letter, 16)) int i
letter System.out.println(i) Note Character
? char
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.

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 operation
  • System.out.println (i) // Displays 3
  • (int) truncates by dropping the fractional part.

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
23
Standard String Processing Loop
for (int i 0 i lt str.length() i) char ch
str.charAt(i) ltprocess chgt
'H'
'e'
'y'
' '
'J'
'o'
'e'
'!'
0 1 2 3 4 5
6 7
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) . . .
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 lt
str.length() i) char ch
str.charAt(i) if (! Character.isDigit(ch))
// Not digit return false
return true // Got through
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

27
Lexicographical Order
"Ann" lt "Bill" lt "bill" // Good idea, bad
Java String str1 "Ann", str2
"Bill" str1.compareTo("Ann") // Returns
0 str1.compareTo(str2) // Returns int lt
0 str2.compareTo(str1) // Returns int gt 0 if
(str1.compareTo(str2) lt 0) // str1 comes
before str2
28
Palindrome, pp. 129130 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 lt middlePosition) if
(s.charAt (forward) ! s.charAt (backward))
return false forward
backward-- return true
29
The Math Class(pp. 134135)
  • 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.

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 operation System.out.pri
ntln (i) // Displays 4
31
Random Numbers
Problem Generate a random integer between 1 and
6 for rolling dice. Math.random() // Returns a
double, d, where 0 lt d lt 1 Math.random() 6
// Returns a double, d, where 0 lt d lt 6 (int)
(Math.random() 6) // Returns an int, i, where
0 lt i lt 5 (int) (Math.random() 6) 1 //
Returns an int, i, where 1 lt i lt 6
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 (aaaaa) // Yields 100,000,008
  • d b aaaaa // Yields 100,000,000
  • Less problem with double than float.

33
CS 303E Class 7 Part 3 Data Structures
IObjects and Classes
"I have a cat named Trash. In the current
political climate 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
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)

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

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

38
Example Class DoubleField
  • Specifies
  • all the data needed for an object (window
    component) of type DoubleField such as the
    components 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.

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
Class
Objects
balance
transaction
interestRate
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.

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.

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.

43
Example Class Student(pp. 159180)
  • 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).

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

45
Declaring the class and data
  • public class ClassName extends Object
  • // Declare Fields or Instance variables
  • private type name1
  • private type name2, name3
  • // etc.

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

a String 3 ints
47
Instantiation Creating an object of a class type
Code 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() ge
orge new Student()
48
Class Student - Behavior
  • What can be done with a Student object from the
    clients perspective?
  • instantiation -- create an object of type Student
  • set the name and the test scores
  • get the name and the test scores
  • get the students average, highest score, lowest
    score, etc.

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

50
Design the methods 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()

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
Write a Comment
User Comments (0)
About PowerShow.com