An Object-Oriented Approach to
Programming Logic and Design
Fourth Edition
Chapter 2
Applications and Data
Objectives
In this chapter, you will learn about:
• Creating an application class with a main()
method
• Programming languages reflecting logic
• Literals, variables, and named constants
• Assigning values to variables
• Arithmetic operations
• Features of good program design
• An Introduction to Structure
An Object-Oriented Approach to Programming Logic and Design
2
Creating an Application Class with
a main()Method
• Application
– Program that executes to accomplish a task
– Term used synonymously with program
• Object-Oriented Programming Languages
– Every programming statement must be part of a class
• Method
– Named set of statements that perform task(s) in an
application
– In a class, all statements are placed in a method
– Application classes contain a main() method
An Object-Oriented Approach to Programming Logic and Design
3
Creating an Application Class with
a main() Method (cont’d)
Figure 2-1 Flowchart and pseudocode for a class with a
main() method that prints “Hello”
An Object-Oriented Approach to Programming Logic and Design
4
Creating an Application Class with
a main() Method (cont’d)
Application Class
• Begins class header with word class followed by
class name
• Ends with word endClass
– No object-oriented programming language uses
endClass
• Class header and ending statement aligned vertically
for easy reading
• Only one header and one endClass statement for
each class
An Object-Oriented Approach to Programming Logic and Design
5
Creating an Application Class with
a main() Method (cont’d)
• Class name
– Any legal identifier
• Identifier
– Name of a programming object (class, method, or variable)
– Different programming languages have different rules for
naming identifiers
An Object-Oriented Approach to Programming Logic and Design
6
Creating an Application Class with
a main() Method (cont’d)
• Common identifier rules
– Can contain letters and digits
– Some languages allow special characters (Ex. hyphen or
underscore)
– May not begin with a digit (most languages)
– May not contain white space (spaces, tabs, line breaks)
– May not be a keyword
– Are case sensitive (Hello, hello, and HELLO are
considered separate identifiers)
• Use descriptive names
An Object-Oriented Approach to Programming Logic and Design
7
Understanding the main()
Method
• Executable programs contain a main() method.
• Set of parentheses always follows method name
• Rules for naming method identifiers follow same
basic rules as class identifiers
• Convention of this text
– method names begin with a lowercase letter and method
ends with a return statement
– For readability, capitalize subsequent words in method
header
• Examples: computePaycheck, startTheGame
An Object-Oriented Approach to Programming Logic and Design
8
Understanding the main()
Method (cont’d)
• Place method’s executable statements between
method header and return statement
• Pseudocode indentation conventions
• Method header and return statement align vertically to show
they are a pair
• Method statements are indented more than class and
endClass statements but less than executable statements
in code
An Object-Oriented Approach to Programming Logic and Design
9
Understanding How Programming
Languages Reflect Logic
Figure 2-2 The Hello class written in the Java programming language
Figure 2-3 The Hello class written in the C# programming language
An Object-Oriented Approach to Programming Logic and Design
10
Understanding How Programming
Languages Reflect Logic (cont’d)
Figure 2-4 The Hello class written in the Visual Basic programming language
An Object-Oriented Approach to Programming Logic and Design
11
Using Literals, Variables, and
Named Constants
• Programs accept input in different ways
– User enters data in an interactive program
– Storage devices provide large amounts of data to batch
programs
• Three different forms of data
– Literals (unnamed constants)
– Variables
– Named constants
An Object-Oriented Approach to Programming Logic and Design
12
Understanding Unnamed, Literal
Constants and Their Data Types
Two types of unnamed constants: numeric and text
• Numeric constant or literal numeric constant
– Number without quotation marks
• Example: 613
– Cannot contain alphabetic characters
• String constant, or literal string constant
– Text enclosed in quotation marks
• Example: “Jenna”
– Also called alphanumeric values
– Can contain digits, punctuation, and other characters
An Object-Oriented Approach to Programming Logic and Design
13
Working with Variables
• Variables
– Named memory locations
– Contents can vary over time
– Hold just one value at any given time
• Examine the doubling statements in the following
pseudocode
Figure 2-5 Statements that input a number, double it, and display the results
An Object-Oriented Approach to Programming Logic and Design
14
Working with Variables (cont’d)
• In most programming languages, must declare a
variable before it can be used
• Variable declaration includes data type and identifier
• Data type describes the following:
– What values the variable can hold
– How the data is stored in computer memory
– What operations can be performed on the data
An Object-Oriented Approach to Programming Logic and Design
15
Working with Variables (cont’d)
• In this text, two data types are used
– num
– string
** First issue with the text
• Must declare variables before using them in a
program
• Sample statements containing declarations.
– num mySalary
– string myName
• ** Not indicative of actual languages.
An Object-Oriented Approach to Programming Logic and Design
16
Primitive Data Types
Type
Meaning
boolean
Represents true/false values
byte
8 bit integer (whole number)
char (character)
16 bit Unicode character
double
64 bit double-precision floating point value
float
32 bit single-precision floating point value
int (integer)
32 bit integer (whole number)
long
64 bit integer (whole number)
short
16 bit integer (whole number)
An Object-Oriented Approach to Programming Logic and Design
17
Integer Types Ranges
Type
Range
Size
byte
-128 to 127
Signed 8-bit integer
short
-32,768 to 32,767
Signed 16-bit integer
int
-2,147,483,648 to 2,147,483,647
Signed 32-bit integer
long
-9,223,372,036,854,775,808 to
Signed 64-bit integer
9,223,372,036,854,775,807
Note: Although char is technically an integer, its use is to represent
characters and will be discussed separately.
An Object-Oriented Approach to Programming Logic and Design
18
Floating Point Ranges
Type
Approximate range
Precision
Size
float
-3.4*1038 to +3.4*1038
6-7 digits
Signed 32-bit
double
-1.70*10308 to +1.7*10308
15-16 digits
Signed 64-bit
An Object-Oriented Approach to Programming Logic and Design
19
Character Data Type
• 16 bit structure to store character data called Unicode.
• char is an unsigned 16-bit value ranging from 0 – 65,535.
• The ASCII character set represents the first 128 values of the
Unicode set (0 – 127).
• Character variables (char) can be assigned a value either by
using a character, or its numeric value.
– char ch = ‘X’;
or
An Object-Oriented Approach to Programming Logic and Design
char ch = 88;
20
Working with Variables (cont’d)
• Initializing the variable
– Provide a starting value for the variable
• Sample statements containing declarations with
initializations
– num yourSalary = 14.55
– string yourName = “Pat”
• If a variable is declared but not initialized
– The variable contains unknown value called garbage
– Usually illegal to use a garbage-holding variable or display
it as output
An Object-Oriented Approach to Programming Logic and Design
21
Working with Variables (cont’d)
• The following complete program declares variables
before they are initialized
Figure 2-6 A complete number-doubling program
An Object-Oriented Approach to Programming Logic and Design
22
Naming Variables
• Choose descriptive, meaningful names
• Interpreter associates names with specific memory
addresses
• To name variables, follow same rules as naming
classes and methods
An Object-Oriented Approach to Programming Logic and Design
23
Understanding a Variable’s Data
Type
• Each variable has a data type: numeric or string
• Numeric variable
– Holds digits and can be used in mathematical operations
– Can hold a decimal point and a sign (plus or minus)
– Example: testScore = 96
• String variable
– Holds text and special characters
– Can hold digits but not used in mathematical operations
– Example: zipcode = “08202”
An Object-Oriented Approach to Programming Logic and Design
24
Understanding a Variable’s Data
Type (cont’d)
• Can assign data to a variable only if correct type
num taxRate = 2.5
num taxRate = “2.5”
OK
invalid
• Can set a variable to the value of another variable of
the same data type
num testScore1
num testScore2
testScore1 = 96
testScore2 = testScore1
An Object-Oriented Approach to Programming Logic and Design
25
Declaring Named Constants
• Similar to a variable, except named constant is
assigned a value only once
• Used to identify values that will not be changed
during program execution
• Make programs easier to understand
• Text’s convention
– All uppercase letters with underscore separating words for
readability
– Example: SALES_TAX
An Object-Oriented Approach to Programming Logic and Design
26
Declaring Named Constants
(cont’d)
• Benefits of using named constants
– Ease of program maintenance
• Change value and all references change automatically
– Naming constant provides type of documentation
– Helps prevent typographical errors
An Object-Oriented Approach to Programming Logic and Design
27
Assigning Values to Variables
• Assignment statement
– Example: myAnswer = myNumber * 2
– Makes the calculation
– Stores the result in memory location: myAnswer
• Assignment operator (=)
–
–
–
–
Binary Operator
Always operates from right to left
Right side is evaluated before the assignment is made
Value to the left must be a memory address
An Object-Oriented Approach to Programming Logic and Design
28
Performing Arithmetic Operations
• Standard arithmetic operators
+ (plus sign) – addition
- (minus sign) – subtraction
* (asterisk) – multiplication
/ (slash) – division
• Sample Valid Assignment Statements
–
–
–
–
someNumber
someNumber
totalScore
totalScore
=
=
=
=
2 * 20/5
anotherNumber + 3
0
totalScore + 10
• Increases the value of totalScore
An Object-Oriented Approach to Programming Logic and Design
29
Performing Arithmetic Operations
(cont’d)
• Sample Invalid Assignment Statements
– 3 + 5 = someNumber
– anotherNumber + 3 = answer
– value on the left side of the assignment operator is not a
memory location.
An Object-Oriented Approach to Programming Logic and Design
30
Performing Arithmetic Operations
(cont’d)
• Rules of operator precedence
– Parentheses evaluated first
– Multiplication and division next, left to right
– Addition and subtraction next, left to right
An Object-Oriented Approach to Programming Logic and Design
31
Features of Good Program Design
• Good practices that make programs easier to write
and maintain
–
–
–
–
–
Use comments where appropriate
Choose meaningful identifiers
Strive to design clear program statements
Write clear prompts and echo input
Maintain good programming habits as skills improve
An Object-Oriented Approach to Programming Logic and Design
32
Features of Good Program Design
• Internal documentation
– Comments that explain and clarify code that are included
within the same documents as the program’s source code.
• External documentation
– Documentation written outside the program
• Using program comments
– Aid in identifying the purpose of variables
– Explain complex calculations
– Allow a new programmer to understand existing code
An Object-Oriented Approach to Programming Logic and Design
33
Choosing Identifiers
• General guidelines
– Variables or constants should be named with nouns or
combination of nouns and adjectives
– Methods should be named with verbs or combined verb
and noun
– Use meaningful names (self-documenting)
– Use pronounceable names
– Use abbreviations sparingly
An Object-Oriented Approach to Programming Logic and Design
34
Choosing Identifiers (cont’d)
• General guidelines (cont’d)
– Avoid digits in a name
– Separate words in long, multi-word identifiers
– For variables that hold status, use a form of the verb “to
be,” such as “is” or “are”
– Constants in all uppercase with underscores between
words
– Different conventions may be dictated by the organization
An Object-Oriented Approach to Programming Logic and Design
35
Designing Clear Statements
• Avoid confusing line breaks
– Most languages are free-form, so arrange code clearly
• Use temporary variables to clarify long statements
–
–
–
–
Temporary variable: an intermediate or work variable
Used during program execution
Not used for input or output
Advantage: if final output is incorrect, can display
temporary results to determine where the problem occurs
An Object-Oriented Approach to Programming Logic and Design
36
Designing Clear Statements
(cont’d)
• Example of using temporary variables
Figure 2-7 Two ways of achieving the same salespersonCommission result
An Object-Oriented Approach to Programming Logic and Design
37
Writing Clear Prompts and Echoing
Input
• Prompts
–
–
–
–
–
Messages that ask the user for a response
Should give clear directions to the user
Should explain how to format response when applicable
Used in command line and GUI interactive programs
Not needed if input comes from a file
• Echoing input
– Repeating input back to the user in a prompt or output
– Useful as an aid in identifying input errors
An Object-Oriented Approach to Programming Logic and Design
38
Designing Clear Statements
(cont’d)
Example: Using prompts and echoing input
Figure 2-10 Program segment that accepts a customer’s name and uses it in the
second prompt
An Object-Oriented Approach to Programming Logic and Design
39
An Introduction to Structure
• Structure
– Basic unit of programming logic
– Three structures: sequence, selection, and
loop
• Sequence structure
– Perform one action after another with no
decision points
– Perform all steps until the sequence ends
– Example: driving directions
Figure 2-11 The
sequence structure
An Object-Oriented Approach to Programming Logic and Design
40
An Introduction to Structure
(cont’d)
• Selection structure
– Follows one of two branches of logic based on a decision
• Loop structure
– Instructions repeat based on a decision
Figure 2-11 The selection structure
An Object-Oriented Approach to Programming Logic and Design
Figure 2-11 The loop structure
41
Figure 2-12 Flowchart of the
NetPayCalculator application
class
Figure 2-13 Typical execution of the
NetPayCalculator program
An Object-Oriented Approach to Programming Logic and Design
42
Summary
• Application: a program that accomplishes a task
• Method: a set of statements that performs tasks in
an application. Example: main() method
• Data values: stored as literals, variables, and named
constants, which are numeric or string
• Variables: named memory locations with contents
that can differ over time
• Data type describes values that a variable can hold
• Declaration statement provides data type and
identifier for a variable
An Object-Oriented Approach to Programming Logic and Design
43
Summary (cont’d)
• Named constant: assigned a value only once
• Four standard arithmetic operators (+, -, *, /)
• Rules of precedence dictate order of arithmetic
operations
• Examples of good programming practices:
–
–
–
–
Including appropriate comments
Choose identifiers wisely
Design clear statements
Write clear prompts and echo input
• Programming structures: sequence, selection & loop
An Object-Oriented Approach to Programming Logic and Design
44
Descargar

An Object-Oriented Approach to Programming Logic and