Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 85

1

T U T O R I A L

Wage Calculator
7
Application
Introducing Algorithms,
Pseudocode and
Program Control
 2009 Pearson Education, Inc. All rights reserved.
2

Outline

7.1 Test-Driving the Wage Calculator Application


7.2 Algorithms
7.3 Pseudocode
7.4 Control Structures
7.5 If...Then Selection Statement
7.6 If...Then...Else Selection Statement and
Conditional If Expressions
7.7 Constructing the Wage Calculator Application
7.8 Assignment Operators
7.9 Formatting Text
7.10 Using the Debugger: The Watch Window

 2009 Pearson Education, Inc. All rights reserved.


3

Objectives

In this tutorial you will learn:


■ Understand basic problem-solving techniques.
■ Understand control structures.
■ Understand and create pseudocode.
■ Use the If...Then and If...Then...Else
selection statements to choose among
alternative actions.
■ Use the assignment operators.
■ Use the debugger’s Watch window.

 2009 Pearson Education, Inc. All rights reserved.


4

Introduction

■ Structured programming
– A technique for organizing program control that
helps you develop applications that are clear and
easier to debug and modify.
– Applicable to most high-level languages, including
Visual Basic.

 2009 Pearson Education, Inc. All rights reserved.


5

7.1 Test-Driving the Wage Calculator Application


Application Requirements

A payroll company calculates the gross earnings per week


of employees. Employees’ weekly salaries are based on the
number of hours they worked and their hourly wages. The
application assumes a standard work week of 40 hours. The
wages for 40 or fewer hours are calculated by multiplying
the employee’s hourly wage by the number of hours
worked. Any time worked over 40 hours in a week is
considered “overtime” and earns time and a half. The total
overtime earned is added to the user’s gross earnings for
the regular 40 hours of work to calculate the total earnings
for that week.
■ This application calculates earnings from hourly
wage and hours worked per week.

 2009 Pearson Education, Inc. All rights reserved.


6
7.1 Test-Driving the Wage Calculator
Application (Cont.)

■ To organize the GUI, we vertically aligned the


TextBoxes on their right sides and made the
TextBoxes the same size (Fig 7.1).
■ We also left aligned the TextBoxes’ descriptive
Labels.

Figure 7.1 | Wage Calculator application.

 2009 Pearson Education, Inc. All rights reserved.


7

GUI Design Tip


When using multiple TextBoxes vertically, align the
TextBoxes on their right sides, and where possible
make the TextBoxes the same size. Left align the
descriptive Labels for such TextBoxes.

 2009 Pearson Education, Inc. All rights reserved.


8
7.1 Test-Driving the Wage Calculator
Application (Cont.)

■ The employee’s earnings are the sum of the


wages for the standard 40-hour work week
(40*10) and the overtime pay (5*10*1.5)
(Fig 7.2).

Figure 7.2 | Calculating wages by clicking the Calculate Button.

 2009 Pearson Education, Inc. All rights reserved.


9

7.2 Algorithms

■ Computing problems can be solved by executing


a series of actions in a specific order.
■ A procedure for solving a problem, called an
algorithm, deals with:
– the actions to be executed and
– the order in which these actions are to be executed

 2009 Pearson Education, Inc. All rights reserved.


10

7.2 Algorithms (Cont.)

■ The following example demonstrates the importance of


correctly specifying the order in which the actions are to be
executed. Consider the “rise-and-shine algorithm” followed
by one junior executive for getting out of bed and going to
work:
– (1) get out of bed,
– (2) take off pajamas,
– (3) take a shower,
– (4) get dressed,
– (5) eat breakfast and
– (6) carpool to work.
■ This routine prepares the executive for a productive day
at the office.
 2009 Pearson Education, Inc. All rights reserved.
11

7.2 Algorithms (Cont.)

■ Suppose that the same steps are performed in a


slightly different order:
– (1) get out of bed,
– (2) take off pajamas,
– (3) get dressed,
– (4) take a shower,
– (5) eat breakfast,
– (6) carpool to work.

 2009 Pearson Education, Inc. All rights reserved.


12

7.2 Algorithms (Cont.)

■ In this case, our junior executive shows up for


work soaking wet.
■ Indicating the appropriate sequence in which to
execute actions is equally crucial in computer
programs.
■ Program control refers to the task of ordering
an application’s statements correctly.

 2009 Pearson Education, Inc. All rights reserved.


13

7.3 Pseudocode

■ Pseudocode is an informal language that helps


you formulate algo­rithms.
– It is convenient and user friendly
– Not an actual computer-programming language.
■ Pseudocode statements are not executed on
computers.
■ Helps you think out an application before
attempting to write it in a programming language.

 2009 Pearson Education, Inc. All rights reserved.


14

Software Design Tip


Pseudocode helps you conceptualize an
application during the application-design process.
Pseudocode statements can be converted to Visual
Basic at a later point.

 2009 Pearson Education, Inc. All rights reserved.


15

7.3 Pseudocode (Cont.)

■ Example of a pseudocode statement:


Assign 0 to the counter
■ The pseudocode statement above can be
converted to the following Visual Basic statement:
counter = 0

 2009 Pearson Education, Inc. All rights reserved.


16

7.3 Pseudocode (Cont.)

■ Pseudocode normally describes only


executable statements—the actions performed
when the corresponding Visual Basic application
is run.
■ An example of a programming statement that is
not executed is a declaration.

 2009 Pearson Education, Inc. All rights reserved.


17

7.4 Control Structures

■ Sequential execution
– Normally, statements in an application are executed one
after another in the order in which they are written.
■ transfer of control
– Occurs when an executed statement does not directly
follow the previously executed statement in the written
application.
■ All programs can be written in terms of only
three control structures:
– the sequence structure,
– the selection structure and
– the repetition structure.
 2009 Pearson Education, Inc. All rights reserved.
18

7.4 Control Structures (Cont.)

■ The sequence structure is built into Visual


Basic—unless directed to act otherwise, the
computer executes Visual Basic statements
sequentially—that is, one after the other in the
order in which they appear in the application.

 2009 Pearson Education, Inc. All rights reserved.


19

7.4 Control Structures (Cont.)

■ The activity diagram in Fig. 7.3 illustrates a typical


sequence structure, in which two calculations are
performed in order.

Figure 7.3 | Sequence structure activity diagram.

 2009 Pearson Education, Inc. All rights reserved.


20

7.4 Control Structures (Cont.)

■ Activity diagrams are part of the Unified


Modeling Language (UML)—an industry
standard for modeling software systems.
■ An activity diagram models the activity (also
called the workflow) of a portion of a software
system.

 2009 Pearson Education, Inc. All rights reserved.


21

7.4 Control Structures (Cont.)

■ Activity diagrams are composed of special-


purpose symbols, such as
– the action-state symbol (a rectangle with its left and
right sides replaced with arcs curving outward)
– the diamond symbol and the small circle symbol
– transition arrows, which represent the flow of the
activity.
■ Like pseudocode, activity diagrams help you
develop and represent algorithms. Activity
diagrams clearly show how control structures
operate.

 2009 Pearson Education, Inc. All rights reserved.


22

7.4 Control Structures (Cont.)

■ The activity diagram in Fig. 7.3 contains two


action states that represent actions to perform.
■ Each action state contains an action expression.
■ The arrows in the activity diagram are called
transition arrows.
– Represent transitions that indicate the order in which the
actions represented by the action states occur.
■ The solid circle located at the top of the activity
diagram represents the activity’s initial state
– The beginning of the workflow before the application
performs the modeled activities.

 2009 Pearson Education, Inc. All rights reserved.


23

7.4 Control Structures (Cont.)

■ The solid circle surrounded by a hollow circle


that appears at the bottom of the activity
diagram represents the final state
– The end of the workflow after the application performs its
activities.
■ In Fig. 7.3, the rectangles with the upper-right
corners folded over are called notes in the UML
– Like comments in Visual Basic applications
– Explanatory remarks that describe the purpose of
symbols in the diagram.
– A dotted line connects each note with the element that
the note describes.
 2009 Pearson Education, Inc. All rights reserved.
24

7.4 Control Structures (Cont.)

Selection Structures
■ A condition is an expression with a true or
false value that is used to make a decision.
■ Conditions are evaluated to determine whether
their value is true or false.
■ These values are of data type Boolean
– Specified in Visual Basic code by using the keywords
True and False.
■ Refer to a condition as a Boolean expression.

 2009 Pearson Education, Inc. All rights reserved.


25

7.4 Control Structures (Cont.)

■ Visual Basic provides three types of selection


structures.
■ The If...Then selection structure performs
(selects) an action (or sequence of actions)
based on
a condition.
– If the condition evaluates to True, the actions specified
by the If...Then structure are executed.
– If the condition evaluates to False, the actions specified
by the If...Then structure are skipped.

 2009 Pearson Education, Inc. All rights reserved.


26

7.4 Control Structures (Cont.)

■ The If...Then...Else selection structure


– …performs an action (or sequence of actions) if a
condition is true
– …performs a different action (or sequence of actions) if
the condition is false.
■ The Select Case structure performs one of
many actions (or sequences of actions),
depending on the value of an expression.

 2009 Pearson Education, Inc. All rights reserved.


27

7.4 Control Structures (Cont.)

■ The If...Then structure is called a single-


selection structure because it selects or ignores
a single action (or a sequence of actions).
■ The If...Then...Else structure is called a
double-selection structure because it selects
between two different actions (or sequences of
actions).
■ The Select Case structure is called a multiple-
selection structure because it selects among
many different actions or sequences of actions.-

 2009 Pearson Education, Inc. All rights reserved.


28

7.4 Control Structures (Cont.)

Repetition Structures
■ Visual Basic provides seven types of repetition
structures for performing a statement or group
of statements repeatedly:
– While...End While
– Do While...Loop
– Do Until...Loop
– Do...Loop While
– Do...Loop Until
– For...Next
– For Each...Next

 2009 Pearson Education, Inc. All rights reserved.


29

7.4 Control Structures (Cont.)

Keywords
■ The words If, Then, Else, End, Select, Case,
While, Do, Until, Loop, For, Next and Each
are all Visual Basic keywords—Appendix E
includes a complete list of Visual Basic keywords.

 2009 Pearson Education, Inc. All rights reserved.


30

7.4 Control Structures (Cont.)

Control Structure Notes


■ Visual Basic has 11 control structures
– the sequence structure,
– three types of selection structures and
– seven types of repetition structures.
– All Visual Basic applications are formed by combining as
many of each type of control structure as is necessary.
■ All Visual Basic control structures are
single-entry/single-exit control structures
– Each has exactly one entry point and one exit point.

 2009 Pearson Education, Inc. All rights reserved.


31

7.4 Control Structures (Cont.)

■ Control structures are attached to one another by


connecting the exit point of one control structure
to the entry point of the next.
– Similar to stacking building blocks, so we call it
control-structure stacking.
– The only other way to connect control structures is
through control-structure nesting, whereby one control
structure can be placed inside another.

 2009 Pearson Education, Inc. All rights reserved.


32

7.5 If...Then Selection Statement

■ A selection statement chooses among alternative


courses of action in an application.
If student’s grade is greater than or equal to 60
Display “Passed”
■ The preceding pseudocode If statement may be
written in Visual Basic as
If studentGrade >= 60 Then
displayLabel.Text = "Passed"
End If

 2009 Pearson Education, Inc. All rights reserved.


33

7.5 If...Then Selection Statement (Cont.)

■ The condition between keywords If and Then


determines whether the statement(s) within the
If...Then statement will execute.
– If the condition is true, the body of the
If...Then statement executes.
– If the condition is false, the body is not executed.

 2009 Pearson Education, Inc. All rights reserved.


34

Common Programming Error


Omitting the Then keyword in an If...Then statement
is a syntax error. The IDE helps prevent this error by
inserting the Then keyword after you write the condition.

 2009 Pearson Education, Inc. All rights reserved.


35

Good Programming Practice


Visual Basic indents the statements inside
If...Then statements to improve readability.

 2009 Pearson Education, Inc. All rights reserved.


36

7.5 If...Then Selection Statement (Cont.)

■ Conditions in If...Then statements can be formed by using


the equality operators and relational operators (also called
comparison operators), which are summarized in Fig. 7.4.
Algebraic equality Visual Basic equality Example of Meaning of
or relational or relational Visual Basic Visual Basic
operators operators condition condition
Relational operators
> > x > y x is greater than y

< < x < y X is less than y

≥ >= x >= y X is greater than or equal to y

≤ <= x <= y X is less than or equal to y

Equality operators
= = x = y X is equal to y

 <> x <> y x is not equal to y

Figure 7.4 | Equality and relational operators.

 2009 Pearson Education, Inc. All rights reserved.


37

Common Programming Error


Adding spaces between the symbols in the operators
<>, >= and <= (as in < >, > =, < =) is a syntax error that
Visual Basic fixes automatically.

 2009 Pearson Education, Inc. All rights reserved.


38

Common Programming Error


Reversal of the operators <>, >= and
<= (as in ><, =>, =<) is a syntax error that
Visual Basic fixes automatically.

 2009 Pearson Education, Inc. All rights reserved.


39

7.5 If...Then Selection Statement (Cont.)

■ Figure 7.5 shows the syntax of the If...Then


statement.
■ A statement’s syntax specifies how the statement
must be formed to compile.

Syntax
If condition Then
[ statements ]
End If

Figure 7.5 | If...Then statement syntax.

 2009 Pearson Education, Inc. All rights reserved.


40

7.5 If...Then Selection Statement (Cont.)

■ Figure 7.6 illustrates the single-selection If...Then


statement.
■ This activity diagram contains the diamond, or decision
symbol, which indicates that a decision is to be made.
■ The two sets of square brackets above or next to the
arrows leading from the decision symbol are called guard
conditions.

Figure 7.6 | If...Then single-selection statement activity diagram.


 2009 Pearson Education, Inc. All rights reserved.
41

7.5 If...Then Selection Statement (Cont.)

■ A decision symbol indicates that the workflow


continues along a path determined by the guard
conditions, which can be true or false.
■ Each transition arrow emerging from a decision
symbol has a guard condition.
– If a particular guard condition is true, the workflow enters
the action state to which that transition arrow points.
– Only one guard condition associated with a particular
decision symbol can be true at once.

 2009 Pearson Education, Inc. All rights reserved.


42
7.6 If...Then...Else Selection Statement
and Conditional If Expressions

■ The If...Then selection statement performs an indicated


action only when the condition evaluates to True;
otherwise, the action is skipped.
■ The If...Then...Else selection statement allows you to
specify that a different action is to be performed when the
condition is true than when the condition is false.
If student’s grade is greater than or equal to 60
Display “Passed”
Else
Display “Failed”
The preceding pseudocode may be written in Visual Basic as
If studentGrade >= 60 Then
displayLabel.Text = "Passed"
Else
displayLabel.Text = "Failed"
End If
 2009 Pearson Education, Inc. All rights reserved.
43

Good Programming Practice


Indent both body statements of an
If...Then...Else statement to improve readability.
[Note: The Visual Basic IDE does this automatically.]

 2009 Pearson Education, Inc. All rights reserved.


44
7.6 If...Then...Else Selection Statement
and Conditional If Expressions (Cont.)

■ A standard indentation convention should be applied


consistently throughout your applications.
■ The body of the Else clause is indented so that it lines up
with the indented body of the If clause.
■ The If...Then...Else selection statement follows the
same general syntax as the If...Then statement
(Fig. 7.7).

Syntax
If condition Then
[ statements ]
Else
[ statements ]
End If

Figure 7.7 | If... Then... Else statement syntax.


 2009 Pearson Education, Inc. All rights reserved.
45
7.6 If...Then...Else Selection Statement
and Conditional If Expressions (Cont.)

■ The preceding If...Then...Else statement can


also be written using a conditional If
expression, as in
displayLabel.Text = If(studentGrade >= 60,
"Passed", "Failed")
■ A conditional If expression starts with the
keyword If and is followed by three expressions
in parentheses—a condition, the value of the
conditional expression if the condition is true and
the value if the condition is false.

 2009 Pearson Education, Inc. All rights reserved.


46
7.6 If...Then...Else Selection Statement
and Conditional If Expressions (Cont.)

■ Figure 7.8 illustrates the flow of control in the


If...Then...Else double-selection statement.

Figure 7.8 | If...Then...Else double-selection statement activity diagram.

 2009 Pearson Education, Inc. All rights reserved.


47
7.6 If...Then...Else Selection Statement
and Conditional If Expressions (Cont.)

■ Nested If...Then...Else statements test


for multiple conditions by placing
If...Then...Else statements inside other
If...Then...Else statements.
If student’s grade is greater than or equal to 90
Display “A”
Else
If student’s grade is greater than or equal to 80
Display “B”
Else
If student’s grade is greater than or equal to 70
Display “C”
Else
If student’s grade is greater than or equal to
60
Display “D”
Else
Display “F”
 2009 Pearson Education, Inc. All rights reserved.
48
Outline

■ The preceding pseudocode may be written in Visual


Basic as shown in Fig. 7.9.
1 If studentGrade >= 90 Then
2 displayLabel.Text = "A"
3 Else
4 If studentGrade >= 80 Then
5 displayLabel.Text = "B"
6 Else
7 If studentGrade >= 70 Then
8 displayLabel.Text = "C"
9 Else
10 If studentGrade >= 60 Then
11 displayLabel.Text = "D"
12 Else
13 displayLabel.Text = "F"
14 End If
15 End If
16 End If
17 End If

 2009 Pearson Education,


Inc. All rights reserved.
49

Good Programming Practice


If there are several levels of indentation, each level
should be indented farther to the right by the same
amount of space.

 2009 Pearson Education, Inc. All rights reserved.


50
Outline

■ Most Visual Basic programmers prefer to use the


ElseIf keyword to write the preceding
If...Then...Else statement, as shown in
Fig. 7.10.
1 If studentGrade >= 90 Then
2 displayLabel.Text = "A"
3 ElseIf studentGrade >= 80 Then
4 displayLabel.Text = "B"
5 ElseIf studentGrade >= 70 Then
6 displayLabel.Text = "C"
7 ElseIf studentGrade >= 60 Then
8 displayLabel.Text = "D"
9 Else
10 displayLabel.Text = "F"
11 End If

 2009 Pearson Education,


Inc. All rights reserved.
51

Common Programming Error


The Else clause must always be last in an
If...Then...Else statement—following an Else
clause with another Else or ElseIf clause is a
syntax error.

 2009 Pearson Education, Inc. All rights reserved.


52
7.6 If...Then...Else Selection Statement
and Conditional If Expressions (Cont.)

■ The two statements are equivalent, but you should


use the latter statement—it avoids deep indentation
of the code.
■ The final portion of the If...Then...Else
statement uses the Else keyword to handle all the
remaining possibilities.
■ The Else clause must always be last in an
If...Then...Else statement—following an Else
clause with another Else or ElseIf clause is a
syntax error.
■ Note that the latter statement requires only one
End If.
 2009 Pearson Education, Inc. All rights reserved.
53

7.7 Constructing the Wage Calculator Application

■ Pseudocode describing the basic operation of the


Wage Calculator application.
When the user clicks the Calculate Button
Retrieve the number of hours worked and hourly wage from
the TextBoxes
If the number of hours worked is less than or equal to
40 hours
Gross earnings equals hours worked times hourly
wage Else
Gross earnings equals 40 times hourly wage plus
hours above 40 times wage and a half
Display gross earnings

 2009 Pearson Education, Inc. All rights reserved.


54
7.7 Constructing the Wage Calculator
Application (cont.)

■ Figure 7.11 lists the actions, controls and events that help


you complete your own version of this application.
■ The Labels in the first row guide the user through the
application.
■ The Button control, calculateButton, is used to
calculate the employee’s wages.
■ The third column of the table specifies that we’ll be using
this control’s Click event to perform the calculations.
■ The TextBoxes contain input from the user. The final
control, earningsResultLabel, is a Label that
displays the application’s output.

 2009 Pearson Education, Inc. All rights reserved.


55
Action/Control/Event (ACE) Table for the
Wage Calculator Application

Action Control Event


Label the application’s controls wageLabel, Application is run
hoursLabel,
earningsLabel
calculateButton Click

Retrieve the number of hours worked and hourly wageTextBox,


hoursTextBox
wage from the TextBoxes

If the number of hours worked is less than or


equal to 40 hours
Gross earnings equals hours worked times
hourly wage

Else
Gross earnings equals 40 times hourly
wage plus hours above 40 times wage and
a half
Display gross earnings earningsResultLabel

Figure 7.11 | Action/Control/Event table for the Wage Calculator application.

 2009 Pearson Education, Inc. All rights reserved.


56
Action/Control/Event (ACE) Table for the
Wage Calculator Application (Cont.)

■ To complete the Wage Calculator application


– add a Click event to the Calculate Button
– declare the variables you need to calculate the
employee’s wages
■ If you forget to add code to this Click event, the
application won’t respond when the user clicks
the Calculate Button.

 2009 Pearson Education, Inc. All rights reserved.


57
Declaring Variables in the Calculate Button’s
Click Event Handler
■ Double click the Calculate Button.
■ Lines 3–6 of Fig. 7.12 display the generated event handler.

Empty event handler

Figure 7.12 | Calculate Button event handler.

– The End Sub keywords (line 6) indicate the end of event


handler calculateButton_Click.
– The End Class keywords (line 7) indicate the end of
class WageCalculatorForm.
 2009 Pearson Education, Inc. All rights reserved.
58
Declaring Variables in the Calculate Button’s
Click Event Handler (Cont.)
■ A Double variable holds numbers with decimal points.
■ Type Decimal is used to store monetary amounts
because this data type minimizes rounding errors in
arithmetic calculations (Fig 7.13).

Variable declarations

Figure 7.13 | Declaring variables of type Double and Decimal.

 2009 Pearson Education, Inc. All rights reserved.


59
Declaring Variables in the Calculate Button’s
Click Event Handler (Cont.)

■ A constant is an identifier whose value cannot be


changed after its initial declaration.
■ Constants are declared with keyword Const
(Fig 7.14).

Constant declaration

Figure 7.14 | Creating a constant.

 2009 Pearson Education, Inc. All rights reserved.


60

Good Programming Practice


Constants (also called named constants) help make
programs more readable by providing names for
constant values.

 2009 Pearson Education, Inc. All rights reserved.


61

Good Programming Practice


Capitalize each letter in the name of a constant;
separate each word in the name with an underscore.

 2009 Pearson Education, Inc. All rights reserved.


62

Determining the User’s Wages

■ The Val function (Fig 7.15) returns the user input as


Doubles.

Variable assignment

Figure 7.15 | Assigning data to variables.

 2009 Pearson Education, Inc. All rights reserved.


63

Error-Prevention Tip
To reduce errors, the IDE sometimes adds keywords for
you. One example is the adding of the keywords
End...If when an If...Then or an
If...Then...Else statement is created. This eliminates
the possibility that such keywords will be forgotten or
misspelled.

 2009 Pearson Education, Inc. All rights reserved.


64

Determining the User’s Wages (Cont.)

■ This If...Then...Else statement (Fig 7.16)


determines whether employees earn overtime in
addition to their usual wages.

If…Then… Else statement

Figure 7.16 | If... Then... Else statement to determine wages.

 2009 Pearson Education, Inc. All rights reserved.


65

Determining the User’s Wages (Cont.)

■ Line 31 (Fig 7.17) assigns the value in earnings to


the Text property of the Label
earningsResultLabel, implicitly converting
earnings from a Decimal
to a string.

Displaying output

Figure 7.17 | Assigning the result to earningsResultLabel.

 2009 Pearson Education, Inc. All rights reserved.


66

Determining the User’s Wages (Cont.)

■ Test the application (Fig 7.18).

Incorrectly formatted output

Figure 7.18 | Wage Calculator with incorrectly formatted output.

 2009 Pearson Education, Inc. All rights reserved.


67

7.8 Assignment Operators

■ Visual Basic provides several assignment


operators for abbreviating assignment statements.
■ The statement
– value = value + 3
■ adds 3 to the value in value, can be abbreviated
with the addition assignment operator += as
– value += 3

 2009 Pearson Education, Inc. All rights reserved.


68

7.8 Assignment Operators (Cont.)

■ The += operator adds the value of the right


operand to the value of the left operand and
stores the result in the left operand.
■ Visual Basic provides assignment operators for
several binary operators, including +, -, *, ^, /
and \.
■ When an assignment statement is evaluated, the
expression to the right of the operator is always
evaluated first, then assigned to the variable on
the left.

 2009 Pearson Education, Inc. All rights reserved.


69

7.8 Assignment Operators (Cont.)

■ Figure 7.19 includes the assignment operators,


sample expressions using these operators and
explanations.
Assignment operators Sample expression Explanation Assigns
Assume: c = 4
+= c += 7 c=c+7 11 to c
-= c -= 3 c=c-3 1 to c
*= c *= 4 c=c*4 16 to c
/= c /= 2 c=c/2 2 to c
\= c \= 3 c=c\3 1 to c
^= c ^= 2 c=c^2 16 to c

Figure 7.19 | Assignment operators.

 2009 Pearson Education, Inc. All rights reserved.


70

Using the Addition Assignment Operator

■ Add an assignment operator to the application’s


code (Fig 7.20).

Addition assignment
operator shortens
statement

Figure 7.20 | Using the addition assignment operator in a calculation.

 2009 Pearson Education, Inc. All rights reserved.


71

7.9 Formatting Text

■ Method String.Format controls how text


displays.
■ Modifying the appearance of text for display
purposes is known as text formatting.
■ String.Format takes as an argument a format
control string, followed by arguments that
indicate the values to be formatted.
■ The format control string argument specifies how
the remaining arguments are to be formatted.

 2009 Pearson Education, Inc. All rights reserved.


72

Formatting the Gross Earnings

■ The format control string, “{0:C}” indicates that


argument 0 should take the format specified by the letter
after the colon; this letter is called the format specifier.
■ The format defined by the uppercase letter C represents
the currency format, which is used to display values as
monetary amounts (Fig 7.21).
■ The effect of the C format specifier varies, depending on
the locale setting of your computer.

Formatting output as currency

Figure 7.21 | Using the Format method to display the result as currency.
 2009 Pearson Education, Inc. All rights reserved.
73

GUI Design Tip


Format all monetary amounts using the
C (currency) format specifier.

 2009 Pearson Education, Inc. All rights reserved.


74

Formatting the Gross Earnings (Cont.)

■ Figure 7.22 shows several format specifiers.


Format Description
Specifier
C Currency. Formats the currency based on the computer’s locale setting. For U.S.
currency, precedes the number with $, separates every three digits with commas
and sets the number of decimal places to two.
E Scientific notation. Displays one digit to the left of the decimal point and six
digits to the right of the decimal point, followed by the character E and a three-
digit integer representing the exponent of a power of 10. For example, 956.2 is
formatted as 9.562000E+002.
F Fixed point. Sets the number of decimal places to two.
G General. Visual Basic chooses either E or F for you, depending on which
representation generates a shorter string.
D Decimal integer. Displays an integer as a whole number in standard base 10
format.
N Number. Separates every three digits with a comma and sets the number of
decimal places to two. (Varies by locale.)

Figure 7.22 | Format specifiers for strings.

 2009 Pearson Education, Inc. All rights reserved.


1 Public Class WageCalculatorForm 75
2 ' handles Click event Outline
3 Private Sub calculateButton_Click(ByVal sender As System.Object, _
4 ByVal e As System.EventArgs) Handles calculateButton.Click
5
6 ' declare variables
7 Dim hours As Double (1 of 2 )
8 Dim wage As Decimal
9 Dim earnings As Decimal
10
11 Const HOUR_LIMIT As Integer = 40 ' declare constant
12 Keyword Const
specifies constant
13 ' assign values from user input
14 hours = Val(hoursTextBox.Text)
15 wage = Val(wageTextBox.Text)
16

 2009 Pearson Education,


Inc. All rights reserved.
17 ' determine earnings 76
18 If hours <= HOUR_LIMIT Then Outline
19 ' if less than or equal to 40 hours, regular wages Condition between
20 earnings = hours * wage keywords If and Then
21 Else
22 ' if over 40 hours, regular wages for first 40
Else body executes
23 earnings = HOUR_LIMIT * wage
when condition evaluates
24 to False
(2 of 2 )
25 ' time and a half for the additional hours
26 earnings += (Hours - HOUR_LIMIT) * (1.5 * wage)
27 End If
Assignment operator assigns left
operand result of adding left and right
28
operands
29 ' assign result to its corresponding Label
30 earningsResultLabel.Text = String.Format(“{0:C}”, earnings)
31 End Sub ' calculateButton_Click
Format result as currency
32 End Class ' WageCalculatorForm

 2009 Pearson Education,


Inc. All rights reserved.
77

7.10 Using the Debugger: The Watch Window

■ The Watch window allows you to examine the value of a


variable or expression.
■ You can use the Watch window to view changes in a
variable’s value as the application executes, or you can
change a variable’s value yourself.
■ Each expression or variable that is added to the Watch
window is called a watch.

 2009 Pearson Education, Inc. All rights reserved.


78

Using the Debugger: The Watch Window

■ Add breakpoints to the application (Fig 7.24).

Figure 7.24 | Breakpoints added to Wage Calculator application.

 2009 Pearson Education, Inc. All rights reserved.


79

Using the Debugger: The Watch Window (Cont.)

■ Run the application (Fig 7.25).

Figure 7.25 | Wage Calculator application.


■ When a breakpoint is reached, application execution is paused,
and the IDE switches into break mode.
■ Once the application has entered break mode, you are free to
explore the values of various variables, using the debugger’s
Watch window.
 2009 Pearson Education, Inc. All rights reserved.
80

Using the Debugger: The Watch Window (Cont.)


■ To display the Watch window, select Debug > Windows >
Watch.
■ To add a watch, you can type an expression into the Name column.
■ The value and type are added by the IDE (Fig. 7.26).
■ The number stored in wage is of type Decimal.
■ You can also highlight a variable name in the code and drag-and-drop
that variable into the Watch window or right click the variable in the
code and select Add Watch.

Figure 7.26 | Watch window.

 2009 Pearson Education, Inc. All rights reserved.


81

Using the Debugger: The Watch Window (Cont.)

■ The Watch window can evaluate arithmetic


expressions.
■ Expressions containing the = symbol are treated
as Boolean expressions instead of assignment
statements (Fig 7.27).

Complex expression

Boolean expression

Invalid expression

Figure 7.27 | Examining expressions.

 2009 Pearson Education, Inc. All rights reserved.


82

Using the Debugger: The Watch Window (Cont.)


■ To remove an expression, simply right click the expression in
the Watch window and select Delete Watch (Fig. 7.28).
■ Alternatively, click a variable in the Watch window and press
the Delete key.

Delete Watch option

Figure 7.28 | Deleting a watch.

 2009 Pearson Education, Inc. All rights reserved.


83

Using the Debugger: The Watch Window (Cont.)

■ Modified values are displayed in red (Fig. 7.29).

Modified value appears


in red

Figure 7.29 | Modified values in Watch window.

 2009 Pearson Education, Inc. All rights reserved.


84

Using the Debugger: The Watch Window (Cont.)

■ The Watch window (Fig 7.30) can be used to


change the value of a variable by entering the
new value in the Value column.
■ This option enables you to test various values to
confirm the behavior of your application.

Value modified directly

Figure 7.30 | Modifying values in a Watch window.

 2009 Pearson Education, Inc. All rights reserved.


85

Using the Debugger: The Watch Window (Cont.)

■ Run the application (Fig 7.31).

Earnings result based


on altered input

Figure 7.31 | Output displayed after the debugging process.

 2009 Pearson Education, Inc. All rights reserved.

You might also like