480 likes | 637 Views
6. Enhancing the Inventory Application Introducing Variables, Memory Concepts and Arithmetic. Outline. 6.1 Test-Driving the Enhanced Inventory Application 6.2 Variables 6.3 Handling the TextChanged Event 6.4 Memory Concepts 6.5 Arithmetic 6.6 Using the Debugger: Breakpoints.
E N D
6 • Enhancing the InventoryApplication • Introducing Variables, Memory Concepts and Arithmetic
Outline • 6.1 Test-Driving the Enhanced InventoryApplication • 6.2 Variables • 6.3 Handling the TextChanged Event • 6.4 Memory Concepts • 6.5 Arithmetic • 6.6 Using the Debugger: Breakpoints
In this tutorial you will learn: Create variables. Handle the TextChanged event. Apply basic memory concepts using variables. Understand the precedence rules of arithmetic operators. Set breakpoints to debug applications. Objectives
6.1 Test-Driving the Enhanced Inventory Application • The inventory manager notices a flaw in your Inventory application. Although the application calculates the correct result, that result continues to display even after new data is entered. The only time the output changes is when the inventory manager clicks the CalculateTotalButton again. You need to alter the Inventoryapplication to clear the result as soon as the user enters new information into either of the TextBoxes, to avoid any confusion over the accuracy of your calculated result.
Test-Driving the Enhanced Inventory Application • Open Inventory3.sln to test-drive the application (Fig. 6.1). Figure 6.1|Inventory application GUI displayed when the application runs.
Test-Driving the EnhancedInventory Application (Cont.) • Enter a value into each TextBox and click CalculateTotal (Fig. 6.2). Figure 6.2| Running the Inventory application.
Test-Driving the EnhancedInventory Application (Cont.) • The result displayed in the Total:Label will be removed (Fig. 6.3) when the user enters a new quantity in either TextBox. Cleared output Label Figure6.3 | Enhanced Inventory application clears output Label after new input.
6.2 Variables • A variable holds data for your application. • Unlike the Text property of a Label, variable values are not shown to the user by default. • Using variables in an application allows you to store and manipulate data. • Variables store data such as numbers, the date, the time and so on. • However, each variable used in Visual Basic corresponds to exactly one type of information. • All variables must be declared by using program code. • Declarations that you’ll make within event handlers begin with the keyword Dim.
Using Variables in the Inventory Application • Open the Inventory application’s template file. • Enter Code view by selecting View>Code (Fig. 6.4). • Lines 8–10 declare that variables cartons, items and result store data of type Integer, using the As keyword. Click event handler Variable declarations Figure6.4 | Declaring variables in event handler calculateButton_Click.
Good Programming Practice • Use only letters and digits as characters for your variable names.
Good Programming Practice • Typically, variable-name identifiers begin with a lowercase letter. Every word in the name after the first word should begin with a capital letter—for example, firstNumber. This is often called camel case.
Using Variables in theInventory Application (Cont.) • Once the user enters numbers and clicks Calculate Total, the values found in the Text property of each TextBox control are converted to numerical values by the Val function. • Line 13 (Fig. 6.5) is read as “cartonsgets the result of the Val function applied to cartonsTextBox.Text.” Assigning user input to variables Figure6.5 | Retrieving numerical input from TextBoxes.
6.2 Variables (Cont.) • The Val function returns a numerical value as data type Double when converting a value retrieved from a TextBox’s Text property. • Data type Double is used to store both whole and fractional numbers. • Normally, Doubles store floating-point numbers, which are numbers with decimal points such as 2.3456and –845.4680.
6.2 Variables (Cont.) • Lines 13–14 implicitly convert the Doubles to Integer values. This process is called implicitconversion because the conversion is performed by Visual Basic without any additional code. • Implicit conversions from Double to Integer are generally considered poor programming practice due to the potential loss of information.
6.2 Variables (Cont.) • Visual Basic defines 15 primitivedata types (listed in Fig. 6.6), such as Integer. • Primitive data type names are also keywords. • Visual Basic also defines the type Object. • Together, the primitive data types and type Object are known as built-indata types. Figure6.6 | Visual Basic built-in data types.
Using Variables in a Calculation • The statement in line 17 (Fig. 6.7) multiplies the Integer variable cartons by items and assigns the result to variable result, using the assignment operator=. • The statement is read as, “resultgets the value of cartons*items.” Calculating anddisplaying the result Figure6.7 | Multiplication, using variables in calculateButton_Click.
Using Variables in a Calculation (Cont.) • Line 20 assigns the calculation’s result to totalResultLabel’s Text property. The Label then displays the result (Fig. 6.8). Result ofcalculation Figure6.8 | Displaying the multiplication result using variables.
Handling the TextChanged Event • Double click the Cartonspershipment:TextBox to generate an event handler for the TextChanged event (Fig. 6.9). • The notation "" in line 28 is called an emptystring, which is a value that does not containany characters. TextChanged event handler Figure6.9 | TextChanged event handler for Cartons per shipment:TextBox.
Handling the TextChanged Event (Cont.) • You want the result cleared regardless of which TextBox changes value first. • Double click the Items per carton:TextBox, and add these lines (Fig. 6.10) to perform the same task as Line 28. Figure6.10 | TextChanged event handler for Itemspercarton:TextBox.
Outline • Figure 6.11 presents the source code for theInventory application. (1 of 2 ) Use keyword Dim to declare variables insidean event handler Assigning a property’s value to a variable
Outline (2 of 2 ) Assigning avariable’s valueto a property Setting a Label’s Text property to an empty string
Good Programming Practice • If a statement is wider than the code editor window, use the line-continuation character to continue it on the next line.
6.4 Memory Concepts • Variable names—such as cartons, items and result—correspond to actual locations in the computer’s memory. • Every variable has a name, type, size and value. cartons = Val(cartonsTextBox.Text) • Suppose that the user enters the characters 12 in the Cartonspershipment:TextBox. When the user clicks CalculateTotal, the user input is converted to a Doubleusing Val, then the Double value is implicitly converted to an Integer.
6.4 Memory Concepts (Cont.) • The assignment then places the Integer value 12 in the location for variable cartons, as shown in Figure 6.12. Figure6.12 | Memory location showing name and value of variable cartons.
6.4 Memory Concepts (Cont.) • Whenever a value is placed in a memory location,this value replaces the value previously stored in that location. • The previous value is overwritten (lost).
6.4 Memory Concepts (Cont.) • Suppose that the user then enters the characters 10 in the Itemspercarton:TextBox and clicks Calculate Total (Fig. 6.13). items=Val(itemsTextBox.Text) Figure6.13 | Memory locations after values for variablescartons and items have been input.
6.4 Memory Concepts (Cont.) • Once the Calculate TotalButton is clicked, line 17 multiplies these values and places their total into variable result. result=cartons*items • This performs the multiplication and replaces result’s previous value.
6.4 Memory Concepts (Cont.) • The values of cartons and items appear exactly as they did before they were used in the calculation of result(Fig. 6.14). • This illustrates that when a value is read from a memory location, the process is nondestructive. Figure6.14 | Memory locations after a multiplication operation.
6.5 Arithmetic • The arithmeticoperators are summarized in Figure 6.15. • Note the use of various special symbols not used in algebra. Figure6.15 | Arithmetic operators.
6.5 Arithmetic (Cont.) • Visual Basic has separate operators for integer division (the backslash, \) and floating-point division (the forward slash, /). • Floating-point division divides two numbers and returns a floating-point number. • The operator for integer division treats its operands as integers and returns an integer result.
6.5 Arithmetic (Cont.) • When floating-point numbers (numbers with decimal points) are used with the integer-division operator, the numbers are first rounded as follows: • numbers ending in .5 are rounded to the nearest even integer—for example, 6.5 rounds down to 6 and 7.5 rounds up to 8 • all other floating-point numbers are rounded to the nearest integer—for example, 7.1 rounds down to 7 and 7.7 roundsup to 8.
Common Programming Error • Attempting to divide by zero is a runtimeerror (that is, an error that has its effect while the application executes). Dividing by zero terminates an application.
6.5 Arithmetic (Cont.) • The modulus operator, Mod, yields the remainderafter division. • Thus, 7 Mod4 yields 3, and 17Mod5 yields 2. • This operator is used most commonly with Integer operands. • The modulus operator can be used to discover whether one number is a multiple of another.
6.5 Arithmetic (Cont.) • Arithmetic expressions in Visual Basic must be written in straight-line form so that you can type them into a computer. • For example, the division of 7.1 by 4.3 must bewritten as 7.1 / 4.3. • Also, raising 3 to the second power cannot be writtenas 32 but is written in straight-line form as 3^2. • Parentheses are used in Visual Basic expressions to group operations in the same manner as in algebraic expressions. To multiply a times the quantity b+c, you write a * ( b + c )
6.5 Arithmetic (Cont.) • Visual Basic applies the operators in arithmetic expressions in a precise sequence, determined by the rulesof operator precedence. • Operators of the same type are applied from left to right.
Rules of Operator Precedence • Operators in expressions contained within a pair of parentheses are evaluated first. • With nested (or embedded) parentheses, the operators contained in the innermost pair of parentheses areapplied first. • Exponentiation is applied next. • Unary positive and negative, + and -, are applied next.
Rules of Operator Precedence (Cont.) • Multiplication and floating-point division operations are applied next. • Integer division is applied next. • Modulus operations are applied next. • Addition and subtraction operations are applied last.
6.5 Arithmetic (Cont.) • Let’s consider several expressions in light of therules of operator precedence. • The following calculates the average of three numbers: Algebra: m = ( a + b + c ) 3 Visual Basic: m = ( a + b + c ) / 3 • The parentheses are required because floating-point division has higher precedence than addition. • The following is the equation of a straight line: Algebra: y = mx + b Visual Basic: y = m * x + b • No parentheses are required due to operator precedence.
6.5 Arithmetic (Cont.) • To develop a better understanding of the rules of operator precedence, consider how the expressiony = ax2 + bx + c is evaluated: • The circled numbers under the statement indicatethe order in which Visual Basic applies the operators. • It is acceptable to place redundant parentheses in an expression to make the expression easier to read. y = ( a * ( x ^ 2 ) ) + ( b * x ) + c
Good Programming Practice • Using redundant parentheses in complex arithmetic expressions can make the expressions easier to read.
6.6 Using the Debugger: Breakpoints • A breakpoint is a marker that can be set at any executable line of code. • When application execution reaches a breakpoint, execution pauses, allowing you to peek inside your application and ensure that there are no logic errors.
Using the Debugger: Breakpoints • To insert a breakpoint in the IDE, either click inside the marginindicatorbar next to a line of code, or right click that line of code and select Breakpoint >InsertBreakpoint Fig. 6.16). • The application is said to be in breakmode when the debugger pauses the application’s execution. Margin indicator bar Breakpoints Figure6.16 | Setting two breakpoints.
Using the Debugger: Breakpoints (Cont.) • After setting breakpoints in the code editor, select Debug > StartDebugging to begin the debugging process (Fig. 6.17, Fig. 6.18). Figure6.17 | Inventory application running. Title bar displays (Debugging) Figure6.18 | Title bar of the IDE displaying (Debugging).
Using the Debugger: Breakpoints (Cont.) • Application execution suspends at the first breakpoint, and the IDE becomes the active window (Fig. 6.19). The yellow arrow to the left of line 17 indicates that this line contains the next statement to execute. Next executable statement Yellow arrow Breakpoints Figure6.19 | Application execution suspended at the first breakpoint.
Using the Debugger: Breakpoints (Cont.) • To resume execution, select Debug>Continue (or press F5). • Note that when you place your mouse pointer over the variable name result, the value that the variable stores is displayed in a QuickInfo box (Fig. 6.20). Quick Info boxdisplays variable result’s value Figure6.20 | Displaying a variable value by placing the mouse pointer over a variable name.
Using the Debugger: Breakpoints (Cont.) • Use the Debug > Continue command to complete the application execution. When there are no more breakpoints at which to suspend execution, the application executes to completion (Fig. 6.21). Figure6.21 | Application output.
Using the Debugger: Breakpoints (Cont.) • To disable a breakpoint, right click a line of code in which a breakpoint has been set, and select Breakpoint >Disable Breakpoint (Fig. 6.22). Disabled breakpoint Figure6.22 | Disabled breakpoint.
Using the Debugger: Breakpoints (Cont.) • To fully remove a breakpoint, right click a line of code in which a breakpoint has been set and select Breakpoint >DeleteBreakpoint. • To remove all breakpoints, select Debug > Delete All Breakpoints from the menu bar.