Download presentation
Presentation is loading. Please wait.
Published byAshlee McCormick Modified over 8 years ago
1
2007 Pearson Education, Inc. All rights reserved. 1 3 3 Introduction to Visual Basic Programming
2
2007 Pearson Education, Inc. All rights reserved. 2 Comment is free, but facts are sacred. — C. P. Scott When faced with a decision, I always ask, “What would be the most fun?” — Peggy Walker Equality, in a social sense, may be divided into that of condition and that of rights. — James Fenimore Coope
3
2007 Pearson Education, Inc. All rights reserved. 3 OBJECTIVES In this chapter you will learn: To write simple Visual Basic programs using code rather than visual programming. To write statements that input data from the keyboard and output data to the screen. To declare and use data of various types. To store and retrieve data from memory. To use arithmetic operators to perform calculations. To use the precedence of arithmetic operators to determine the order in which operators are applied. To write decision-making statements. To use equality and relational operators to compare operands. To use message dialogs to display messages.
4
2007 Pearson Education, Inc. All rights reserved. 4 3.1 Introduction 3.2 Displaying a Line of Text 3.3 Creating Your First Console Application in Visual Basic Express 3.4 Displaying a Single Line of Text with Multiple Statements 3.5 Adding Integers 3.6 Memory Concepts 3.7 Arithmetic 3.8 Decision Making: Equality and Relational Operators 3.9 Using a Message Dialog to Display a Message 3.10 (Optional) Software Engineering Case Study: Examining the ATM Requirements Document 3.11 Wrap-Up 3.12 Web Resources
5
2007 Pearson Education, Inc. All rights reserved. 5 3.1 Introduction Console Application – Input and output text in console window Windows 95/98/ME: MS-DOS prompt Other version of Windows: Command Prompt
6
2007 Pearson Education, Inc. All rights reserved. 6 3.2 Displaying a Line of Text Sample program – Displays a line of text – Illustrates several important VB language features
7
2007 Pearson Education, Inc. All rights reserved. 7 Outline Welcome1.vb Entry point of program Console.WriteLine outputs to screen End subroutine Main
8
2007 Pearson Education, Inc. All rights reserved. 8 3.2 Displaying a Line of Text (Cont.) – Comments start with: ‘ Comments ignored during program execution Document and describe code Provides code readability 1 ‘ Fig. 3.1: Welcome1.vb 2 ‘ Simple Visual Basic program.
9
2007 Pearson Education, Inc. All rights reserved. 9 3.2 Displaying a Line of Text (Cont.) Blank line – Makes program more readable – Blank lines, spaces, and tabs are white-space characters – Ignored by compiler Module declaration for module Welcome1 – Modules are logical grouping of methods that simplify program organization – Keyword: words reserved for use by Visual Basic Module keyword followed by module name - Must have corresponding End Module statement – Naming classes: capitalize every word (Pascal casting) SampleClassName 3 4 Module FirstWelcome
10
2007 Pearson Education, Inc. All rights reserved. 10 Fig. 3.2 | Keywords in Visual Basic. (Part 1 of 3.)
11
2007 Pearson Education, Inc. All rights reserved. 11 Fig. 3.2 | Keywords in Visual Basic. (Part 2 of 3.)
12
2007 Pearson Education, Inc. All rights reserved. 12 Fig. 3.2 | Keywords in Visual Basic. (Part 3 of 3.)
13
2007 Pearson Education, Inc. All rights reserved. 13 3.2 Displaying a Line of Text (Cont.) – Visual Basic identifier Series of characters consisting of letters, digits and underscores ( _ ) Does not begin with a digit, has no spaces Examples: Welcome1, identifier, _value, button7 - 7button is invalid VB is not case sensitive (capitalization does not matters) - a1 and A1 are the same
14
2007 Pearson Education, Inc. All rights reserved. 14 Common Programming Error 3.1 Identifiers cannot be keywords, so it is an error, for example, to choose any of the words in Fig. 3.2 as a Module name. The Visual Basic compiler helps you locate such errors in your programs. Though keywords cannot be used as identifiers, they can be used in strings and comments.
15
2007 Pearson Education, Inc. All rights reserved. 15 Good Programming Practice 3.1 Use whitespace to enhance program readability.
16
2007 Pearson Education, Inc. All rights reserved. 16 3.2 Displaying a Line of Text (Cont.) – Part of every Visual Basic application Applications begin executing at Main - Sub indicates that Main is a method - VB applications contain one or more methods Exactly one method must be called Main – Methods can perform tasks and return information Sub means Main returns no information - Abbreviation for subroutine - Must have corresponding End Sub statement 6 Sub Main()
17
2007 Pearson Education, Inc. All rights reserved. 17 Good Programming Practice 3.2 Indent the entire body of each method declaration one additional “level” of indentation. This emphasizes the structure of the method, improving its readability. In this text, one level of indentation is set to three spaces—this keeps the code readable yet concise.
18
2007 Pearson Education, Inc. All rights reserved. 18 3.2 Displaying a Line of Text (Cont.) – Instructs computer to perform an action Prints string of characters - String: series characters inside double quotes White-spaces in strings are not ignored by compiler – Method Console.WriteLine Standard output Print to command window (i.e., MS-DOS prompt) Displays line of text
19
2007 Pearson Education, Inc. All rights reserved. 19 3.3 Creating Your First Console Application in Visual Basic Express Creating the Console Application – Open New Project dialog and select Console Application (Fig. 3.3-3.4) Modifying the Editor Settings to Display Line Numbers – Visual Basic Express provides many ways to personalize your coding experience (Fig. 3.5) Changing the Name of the Program File – Change the File Name property in the Solution Explorer (Fig. 3.6) Setting the Startup Object – Each Visual Basic project has a startup object that specifies where the application begins executing. (Fig. 3.7)
20
2007 Pearson Education, Inc. All rights reserved. 20 Fig. 3.3 | Creating a Console Application with the New Project dialog.
21
2007 Pearson Education, Inc. All rights reserved. 21 Fig. 3.4 | IDE with an open console application.
22
2007 Pearson Education, Inc. All rights reserved. 22 Fig. 3.5 | Modifying the IDE settings.
23
2007 Pearson Education, Inc. All rights reserved. 23 Fig. 3.6 | Renaming the program file in the Properties window.
24
2007 Pearson Education, Inc. All rights reserved. 24 Fig. 3.7 | Setting the startup object.
25
2007 Pearson Education, Inc. All rights reserved. 25 3.3 Creating Your First Console Application in Visual Basic Express (Cont.) Writing Code – IntelliSense: Lists a class’s members after a dot (Fig. 3.8-3.9) Saving the Application – Specify the directory where you want to save the project (Fig. 3.10) Compiling and Running the Application (Fig. 3.11) – Compiler compiles code into files Ex:.exe (executable),.dll (dynamic link library), and more! Running the Application from the Command Prompt – Alternate way to go run a program without using the IDE (Fig. 3.12-3.13)
26
2007 Pearson Education, Inc. All rights reserved. 26 Fig. 3.8 | IntelliSense feature of Visual Basic Express.
27
2007 Pearson Education, Inc. All rights reserved. 27 Fig. 3.9 | Parameter Info window.
28
2007 Pearson Education, Inc. All rights reserved. 28 Fig. 3.10 | Save Project dialog.
29
2007 Pearson Education, Inc. All rights reserved. 29 Fig. 3.11 | Executing the program shown in Fig. 3.1.
30
2007 Pearson Education, Inc. All rights reserved. 30 Fig. 3.12 | Executing the program shown in Fig. 3.1 from a Command Prompt.
31
2007 Pearson Education, Inc. All rights reserved. 31 Fig. 3.13 | Executing the program shown in Fig. 3.1 from a Command Prompt.
32
2007 Pearson Education, Inc. All rights reserved. 32 3.3 Creating Your First Console Application in Visual Basic Express (Cont.) Syntax Errors, Error Messages and the Error List Window – Syntax Error A violation of Visual Basic rules for creating correct application – Error List Window (Fig. 3.14) Window where the descriptions of the errors are located Note: Red underline indicts a syntax error
33
2007 Pearson Education, Inc. All rights reserved. 33 Error-Prevention Tip 3.1 One syntax error can lead to multiple entries in the Error List window. Each error that you address could eliminate several subsequent error messages when you recompile your program. So, when you see a particular error you know how to fix, correct it and recompile—this may make the other errors disappear.
34
2007 Pearson Education, Inc. All rights reserved. 34 Fig. 3.14 | Syntax error indicated by the IDE.
35
2007 Pearson Education, Inc. All rights reserved. 35 3.4 Displaying a Single Line of Text with Multiple Statements Modified program – SecondWelcome.cs (Fig. 3.15) produces same output as FirstWelcome.cs (Fig. 3.1) – Using different code – Line 7 displays “Welcome to ” with cursor remaining on printed line – Line 8 displays “Visual Basic! ” on same line with cursor on next line 8 Console.Write( "Welcome to "); 9 Console.WriteLine( “ Visual Basic!" );
36
2007 Pearson Education, Inc. All rights reserved. 36 Outline Welcome2.vb Cursor stays on same line after outputting Cursor moves to next line after outputting
37
2007 Pearson Education, Inc. All rights reserved. 37 3.5 Adding Integers Variables – Location in memory that stores a value Declare with name and type before use – In most cases, uses keyword Dim when declaring variables – Variable name: any valid identifier Initialize variable in its declaration – Equal sign
38
2007 Pearson Education, Inc. All rights reserved. 38 Outline Addition.vb Declare variables number1, number2 and sum. Assign user’s input to number1. Calculate the sum of the variables number1 and number2, assign result to sum. Display the sum. Assign user’s input to number2.
39
2007 Pearson Education, Inc. All rights reserved. 39 3.5 Adding Integers (Cont.) – Declare variable number1, number2 and sum of type Integer Integer holds integer values (whole numbers): i.e., 0, -4, 97 Types Single, Double and Decimal can hold decimal numbers Type Char can hold a single character, i.e.: x, $, 7 Integer, Float, Double, Decimal and Char are primitive types – Can declare multiple variables of the same type in one declaration Use comma-separated list 9 Dim number1 As Integer 10 Dim number2 As Integer 11 Dim sum As Integer
40
2007 Pearson Education, Inc. All rights reserved. 40 3.5 Adding Integers (Cont.) – Message called a prompt: directs user to perform an action – ReadLine waits for user to type a string of characters – Result of call to ReadLine given to number1 using assignment operator = = is a binary operator - Takes two operands Expression on right evaluated and assigned to variable on left Read as: number1 gets the value of Console.ReadLine() 14 Console.Write( "Enter first integer: " ) 15 number1 = Console.ReadLine()
41
2007 Pearson Education, Inc. All rights reserved. 41 3.5 Adding Integers (Cont.) – Similar to previous statement Prompts the user to input the second integer – Similar to previous statement Assign variable number2 to second integer input – Assignment statement Calculates sum of number1 and number2 (right hand side) Uses assignment operator = to assign result to variable sum Read as: sum gets the value of number1 + number2 number1 and number2 are operands 18 Console.Write( "Enter second integer: " ) 19 number2 = Console.ReadLine() 21 sum = number1 + number2 ‘ add the numbers
42
2007 Pearson Education, Inc. All rights reserved. 42 3.5 Adding Integers (Cont.) – Use Console.WriteLine to display results – & is the string concatenation operator – Calculations can also be performed inside WriteLine – Parentheses around the expression number1 + number2 are not required 23 Console.WriteLine( “The sum is : " & sum ) ‘ display the sum Console.WriteLine( "Sum is {0} " & ( number1 + number2 ) );
43
2007 Pearson Education, Inc. All rights reserved. 43 Fig. 3.17 | Primitive types in Visual Basic.
44
2007 Pearson Education, Inc. All rights reserved. 44 Good Programming Practice 3.3 Choosing meaningful variable names helps a program to be “self-documenting” (i.e., the program can be understood by others without the use of documentation manuals or excessive comments).
45
2007 Pearson Education, Inc. All rights reserved. 45 Good Programming Practice 3.4 A common convention (and the one used in this book) is to have the first word in a variable-name identifier begin with a lowercase letter. Every word in the name after the first word should begin with a uppercase letter. For example, identifier firstNumber has a capital N beginning its second word, Number. We use a similar convention for module names, except that the first letter of the first word is also capitalized. Although identifiers are not case sensitive, using these conventions helps make your programs more readable. In this book, we use widely adopted Visual Basic naming conventions.
46
2007 Pearson Education, Inc. All rights reserved. 46 Good Programming Practice 3.5 Declaring each variable on a separate line allows for easy insertion of an end-of-line comment next to each declaration. We will follow this convention.
47
2007 Pearson Education, Inc. All rights reserved. 47 Good Programming Practice 3.6 Place spaces on either side of a binary operator to make the operator stand out and improve the readability of the statement.
48
2007 Pearson Education, Inc. All rights reserved. 48 Fig. 3.18 | Dialog displaying a run-time error.
49
2007 Pearson Education, Inc. All rights reserved. 49 Good Programming Practice 3.7 Follow a method’s End Sub with an end-of-line comment containing the name of the method that the End Sub terminates.
50
2007 Pearson Education, Inc. All rights reserved. 50 3.6 Memory Concepts Variables – Every variable has a name, a type, a size and a value Name corresponds to location in memory – When new value is placed into a variable, replaces (and destroys) previous value – Reading variables from memory does not change them
51
2007 Pearson Education, Inc. All rights reserved. 51 Fig. 3.19 | Memory location showing name and value of variable number1.
52
2007 Pearson Education, Inc. All rights reserved. 52 Fig. 3.20 | Memory locations after values for variables number1 and number2 have been input.
53
2007 Pearson Education, Inc. All rights reserved. 53 Fig. 3.21 | Memory locations after an addition operation.
54
2007 Pearson Education, Inc. All rights reserved. 54 3.7 Arithmetic Arithmetic calculations used in most programs – Usage * for multiplication \ for integer division - Any fractional part is truncated / for floating-point division Mod for modulus +, - – Integer division truncates remainder 7 \ 5 evaluates to 1 – Remainder operator Mod returns the remainder 7 Mod 5 evaluates to 2
55
2007 Pearson Education, Inc. All rights reserved. 55 Fig. 3.22 | Arithmetic operators.
56
2007 Pearson Education, Inc. All rights reserved. 56 3.7 Arithmetic (Cont.) Operator precedence – Some arithmetic operators act before others (i.e., multiplication before addition) Use parenthesis when needed or for clarity – Example: Find the average of three variables a, b and c Do not use: a + b + c / 3 Use: ( a + b + c ) / 3
57
2007 Pearson Education, Inc. All rights reserved. 57 Common Programming Error 3.2 Using the integer division operator ( \ ) when the floating-point division operator ( / ) is expected (i.e., when one or both of the operands is a floating-point value) can lead to incorrect results.
58
2007 Pearson Education, Inc. All rights reserved. 58 Error-Prevention Tip 3.2 Ensure that each integer division operator has only integer operands.
59
2007 Pearson Education, Inc. All rights reserved. 59 Fig. 3.23 | Precedence of arithmetic operators.
60
2007 Pearson Education, Inc. All rights reserved. 60 Good Programming Practice 3.8 Redundant parentheses can make complex expressions easier to read.
61
2007 Pearson Education, Inc. All rights reserved. 61 Error-Prevention Tip 3.3 When you are uncertain about the order of evaluation in a complex expression, use parentheses to force the order, as you would do in an algebraic expression. Doing so can help avoid subtle bugs.
62
2007 Pearson Education, Inc. All rights reserved. 62 Fig. 3.24 | Order in which a second-degree polynomial is evaluated.
63
2007 Pearson Education, Inc. All rights reserved. 63 3.8 Decision Making: Equality and Relational Operators Condition – Expression can be either True or False If…Then statement – Simple version in this section, more detail later – If a condition is True, then the body of the If…Then statement executed – Control always resumes after the If…Then statement – Conditions in If…Then statements can be formed using equality or relational operators (Fig. 3.25)
64
2007 Pearson Education, Inc. All rights reserved. 64 Fig. 3.25 | Equality and relational operators.
65
2007 Pearson Education, Inc. All rights reserved. 65 Common Programming Error 3.3 It is a syntax error to reverse the symbols in the operators <>, >= and, =< ).
66
2007 Pearson Education, Inc. All rights reserved. 66 Outline Comparison.vb (1 of 3 )
67
2007 Pearson Education, Inc. All rights reserved. 67 Outline Comparison.vb (2 of 3 ) Test for equality, display result using WriteLine. Compares two numbers using relational operator <. Compares two numbers using relational operators > and <=.
68
2007 Pearson Education, Inc. All rights reserved. 68 Outline Comparison.vb (3 of 3 ) Compares two numbers using relational operator <.
69
2007 Pearson Education, Inc. All rights reserved. 69 3.8 Decision Making: Equality and Relational Operators (Cont.) – Line 4: begins module Comparison declaration – Lines 9-10: declare Integer s variables – Lines 13-14: prompt the user to enter the first integer and input the value – Lines 17-18: prompt the user to enter the second integer and input the value
70
2007 Pearson Education, Inc. All rights reserved. 70 3.8 Decision Making: Equality and Relational Operators (Cont.) – If…Then statement to test for equality using ( = ) If variables equal (condition true) - Line 21 executes If variables not equal, statement skipped Empty statement - No task is performed – Lines 24-26, 28-30, 32-34, 37-39 and 42-44 Compare number1 and number2 with the operators <>,, =, respectively 20 If number1 = number2 Then ‘ number1 is equal to number2 21 Console.WriteLine( number1 & “ = ” & number2 ) 22 End If
71
2007 Pearson Education, Inc. All rights reserved. 71 Good Programming Practice 3.9 Indent the statement in the body of an If... Then statement to emphasize the body statement and enhance program readability.
72
2007 Pearson Education, Inc. All rights reserved. 72 Fig. 3.27 | Precedence of the operators introduced in this chapter.
73
2007 Pearson Education, Inc. All rights reserved. 73 Outline SquareRoot.vb Assign the square root of 2 to root Show results via a message dialog
74
2007 Pearson Education, Inc. All rights reserved. 74 3.9 Using a Message Dialog to Display a Message Message Dialogs – Windows that display messages to the user – Class MessageBox System.Windows.Forms - Classes that help programmers define GUIs for their application FCL classes are grouped by functionality into namespaces – Some classes need to be added to the project before use; located in an assembly Add Reference Imports statement indicates which namespace to use – The IDE will implicitly add various references depending on the type of a project.
75
2007 Pearson Education, Inc. All rights reserved. 75 3.9 Using a Message Dialog to Display a Message (Cont.) Line continuation – Any statement in Visual Basic can be written as more than a line – Use the character “_” One whitespace character must precede the character
76
2007 Pearson Education, Inc. All rights reserved. 76 Common Programming Error 3.4 Splitting a statement over several lines without including the line-continuation character is a syntax error.
77
2007 Pearson Education, Inc. All rights reserved. 77 Common Programming Error 3.5 Failure to precede the line-continuation character ( _ ) with at least one whitespace character is a syntax error.
78
2007 Pearson Education, Inc. All rights reserved. 78 Common Programming Error 3.6 Placing anything, including comments, on the same line after a line-continuation character is a syntax error.
79
2007 Pearson Education, Inc. All rights reserved. 79 Common Programming Error 3.7 Splitting a statement in the middle of an identifier or string is a syntax error.
80
2007 Pearson Education, Inc. All rights reserved. 80 Good Programming Practice 3.10 If a single statement must be split across lines, choose breaking points that make sense, such as after a comma in a comma-separated list or after an operator in a lengthy expression. If a statement is split across two or more lines, indent all subsequent lines with one level of indentation.
81
2007 Pearson Education, Inc. All rights reserved. 81 Good Programming Practice 3.11 Place a space after each comma in a method’s argument list to make method calls more readable.
82
2007 Pearson Education, Inc. All rights reserved. 82 Fig. 3.29 | Message dialog displayed by calling MessageBox.Show.
83
2007 Pearson Education, Inc. All rights reserved. 83 Fig. 3.30 | Obtaining documentation for a class by using the Index dialog.
84
2007 Pearson Education, Inc. All rights reserved. 84 Fig. 3.31 | Documentation for the MessageBox class.
85
2007 Pearson Education, Inc. All rights reserved. 85 Common Programming Error 3.8 Including a namespace with the Imports statement without adding a reference to the proper assembly results in a compilation error.
86
2007 Pearson Education, Inc. All rights reserved. 86 Fig. 3.32 | Viewing a project’s references.
87
2007 Pearson Education, Inc. All rights reserved. 87 Fig. 3.33 | Adding an assembly reference to a project in the Visual Basic 2005 Express IDE.
88
2007 Pearson Education, Inc. All rights reserved. 88 3.10 (Optional) Software Engineering Case Study: Examining the Requirements Document Object-oriented design (OOD) process using UML – Chapters 4 to 9, 11 Object-oriented programming (OOP) implementation – Appendix J
89
2007 Pearson Education, Inc. All rights reserved. 89 Fig. 3.34 | Internet Explorer window with GUI components.
90
2007 Pearson Education, Inc. All rights reserved. 90 Fig. 3.35 | Automated teller machine user interface.
91
2007 Pearson Education, Inc. All rights reserved. 91 Fig. 3.36 | ATM main menu.
92
2007 Pearson Education, Inc. All rights reserved. 92 Fig. 3.37 | ATM withdrawal menu.
93
2007 Pearson Education, Inc. All rights reserved. 93 3.10 (Optional) Software Engineering Case Study: Examining the Requirements Document (Cont.) Analyzing the ATM System – Requirements gathering – Software life cycle Waterfall model: Perform each stage once in succession Iterative model: Repeat one or more stages several times – Use case modeling Use Case Diagram – Model the interactions between clients and its use cases – Actor External entity
94
2007 Pearson Education, Inc. All rights reserved. 94 Fig. 3.38 | Use case diagram for the ATM system from the user’s perspective.
95
2007 Pearson Education, Inc. All rights reserved. 95 Fig. 3.39 | Use case diagram for a modified version of our ATM system that also allows users to transfer money between accounts.
96
2007 Pearson Education, Inc. All rights reserved. 96 3.10 (Optional) Software Engineering Case Study: Examining the Requirements Document (Cont.) UML diagram types (UML 2 specifies 13 diagram types) – Model system structure and behavior Use case diagrams - Model interactions between user and a system Class diagram - Models classes, or “building blocks” of a system State machine diagrams - Model the ways in which an object changes state Activity diagrams - Models an object’s activity during program execution Communication diagrams (collaboration diagrams) - Models the interactions among objects - Emphasize what interactions occur Sequence diagrams - Models the interactions among objects - Emphasize when interactions occur
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.