1 / 43

# Unit 2 Variables and Calculations Chapter 3 Input, Variables, Constants, and Calculations - PowerPoint PPT Presentation

Unit 2 Variables and Calculations Chapter 3 Input, Variables, Constants, and Calculations. Chapter 3 Topics. This chapter covers the use of text boxes to gather input from users It also discusses the use of variables named constants intrinsic functions mathematical calculations.

I am the owner, or an agent authorized to act on behalf of the owner, of the copyrighted work described.

## PowerPoint Slideshow about ' Unit 2 Variables and Calculations Chapter 3 Input, Variables, Constants, and Calculations' - mills

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

### Unit 2Variables and CalculationsChapter 3Input, Variables, Constants, and Calculations

• This chapter covers the use of text boxes to gather input from users

• It also discusses the use of

• variables

• named constants

• intrinsic functions

• mathematical calculations

In This Section, We Use the Textbox Control to Gather Input That the User Has Typed on the Keyboard

### Gathering Text Input

Placing Text into a Label That the User Has Typed on the Keyboard

• We have done this already:lblSet.Text = "Place this text in a TextBox"

• The lblSet.Text is in the form: Object.Property

• The text can come from a textBox where the user has typed in input: lblSet.Text = txtInput.Text

• Notice two use of the form: Object.Property

Clearing a Text Box That the User Has Typed on the Keyboard

• This can be done with an assignment: txtInput.Text = ""

• Two adjacent quote marks yields a null string

• So this statement replaces whatever text that may have been in txtInput with "nothing" -- a string with no characters in it

• This can be done with a method: txtInput.Clear()

• Clear is called a Method

• Methods do actions -- here clearing the text

• The syntax is similar to that of referring to a Property: Object.Method

String Concatenation That the User Has Typed on the Keyboard

• In our code we will often need to combine two or more strings into a longer one

• This operation is called "Concatenation"

• Concatenation is signaled with the operator '&' much in the same way that addition is signaled by the operator '+‘

• Say our user has entered their name into txtUserName, a TextBox

• In label lblGreeting we want to say, Hello

• Simply:lblGreeting.Text = "Hello " & txtUserName.Text

• Put "Hello" on the front of the user's name and place the result into lblGreeting

The Focus Method That the User Has Typed on the Keyboard

• For a control to have the focus means that it is ready to receive the user's input

• In a running form, one of the controls always has the focus

• The control with the focus may be set by program control using the Focus Method:txtUserName.Focus()

• You can tell which control has focus by its characteristics:

• When a TextBox has focus, it will have a blinking cursor or the text inside of the box is highlighted

• When a button, radio button, or a check box has focus, it will have a thin dotted line around the control

Controlling a Forms Tab Order That the User Has Typed on the Keyboardwith the TabIndex Property

• Stepping the focus from one control to another can be done using the Tab Key

• This order is set for a control relative to others by the value of the TabIndex Property

• With each Tab Key hit, the focus will step to the control with the next highest value of the TabIndex Property

Assigning Keyboard Access Keys That the User Has Typed on the Keyboardto Buttons

• Say your form had a button with the text "Save" on it

• Any you wished to allow the user to be able to hit Alt-S to activate that button

• Simply change the button text to "&Save"

• The '&' tells Visual Basic .NET to use Alt-S as an access key

'&' is a Special Character That the User Has Typed on the Keyboardin Button Labels

• Note that the '&' in "&Save" does not display on the button

• It simply establishes the Alt Key access

• In order to actually display an '&' on a button, one must enter it as "&&" (then one will appear and will not cause an Alt Key access to be established)

Using Access Keys with Labels That the User Has Typed on the Keyboard

• Want to establish an access key for a TextBox

• The previous technique will not work because the text of a TextBox is normally a changing value

• However, there is a way to accomplish the same effect

• For a Label that immediately precedes a TextBox

• Assign that Label an access key (labels do not normally have access keys)

• Set the UseMnemonic Property to True

• When the user activates the Label's access key, the following TextBox will receive the focus

Setting the Accept Button That the User Has Typed on the Keyboard

• The Accept Button is the one that implicitly will be activated if the user hits the Enter Key

• The AcceptButton Property designates which button on the form is to behave in this manner

Setting the Cancel Button That the User Has Typed on the Keyboard

• The Cancel Button is the one that implicitly will be activated if the user hits the Escape Key

• The CancelButton Property designates which button on the form is to behave in this manner

An Application Uses Variables to Hold Information So It May Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

### Variables

Why Have Variables? Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• A variable is a storage location in the computer’s memory, used for holding information while the program is running

• The information that is stored in a variable may change, hence the name “variable”

What Can You Do With Variables? Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• Copy and store values entered by the user, so they may be manipulated

• Perform arithmetic on values

• Test values to determine that they meet some criterion

• Temporarily hold and manipulate the value of a control property

• Remember information for later use in the program

How to Think About Variables Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• You the programmer make up a name for the variable

• Visual Basic .NET associates that name with a location in the computer's RAM

• The value currently associated with the variable is stored in that memory location

Setting the Value of a Variable Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• An assignment statement is used to set the (new) value of a variable, as in:length = 112 greeting = "Good Morning " & txtName.Text

Variable Declarations Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• A variable declaration is a statement that causes Visual Basic .NET to create a variable in memory

• As inDim length As Integer

Declaration Syntax Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• The official syntax is Dim VariableName As DataTypewhere

• Dim (stands for Dimension) is a keyword

• VariableName is the name to be used

• As is a keyword

• DataType is the type of the variable and will be one of many possible keywords

Boolean Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

Byte

Char

Date

Decimal

Double

Integer

Long

Object

Short

Single

String

Visual Basic .NET Data Types

Variable Naming Rules Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• The first character of a variable name must be a character or an underscore

• Subsequent characters may be either of those plus the numeric digits

• Thus variable names cannot contain spaces or periods (or many other kinds of characters)

• Variable names must not be keywords

Variable Naming Conventions Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• Each variable name should describe its use, e.g., itemsOrdered

• When multiple words are used in a name, capitalize the initials, except for the first one (again, itemsOrdered)

• As noted earlier, certain names should have a specific prefix, e.g., btn

Auto List Feature Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• As you are entering your Visual Basic .NET program, VB will often aid you by offering a list of choices for that could be entered next

• Right after you type "As" in a variable declaration, Visual Basic .NET will offer you a list of all of the established data types

• Either choose one or keep typing

Variable Default Values Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• When a variable is first created in memory, Visual Basic .NET assigns it a default value

• numeric types are given a value of zero

• strings are given a value of Nothing

• dates default to 12:00:00 AM January 1,1

Initialization of Variables Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Usevia the Declaration

• It is preferable to establish your program's own initial value for variables that will not otherwise be given values before they are used

• In the declaration, simply append " = value"Dim length As Integer = 112

Scope of a Variable Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• A variable’s scope is the part of the program where the variable is visible and may be accessed by programming statements

• The scope of a variable begins where it is declared

• And extends to the end of the procedure in which it appears

• This variable is called local

• The variable is not visible outside of the procedure and its name cannot be declared again within the same procedure

Lifetime of a Variable Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• The storage for a variable is created upon each use of the procedure

• The storage for a variable is destroyed as soon as the procedure finishes executing

Setting a Specific Date Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• This can be done a number of ways:startDate = #12/3/2002 1:00:00 AM#startDate = System.Convert.ToDateTime( "12/3/2002 1:00:00 AM")

Setting the Current Date/Time Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• A series of keywords yields the date and time or just one or the other:

• Now startTime = Now

• TimeOfDay startTime = TimeOfDay

• Today startTime = Today

The Val Function Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• Suppose you wish to use text input as a number:number = txtInput.Text

• This will work without a run time error as long as txtInput.Text is the text equivalent of a numerical value (like "45")

• If it is not, there will be a run time error

• The Val function is more lenient on conversions from text to numeric values

• If the initial characters form a numeric value, it will return that

• Otherwise, it will return a value of zero

The Val Function, II Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• Argument Val(Argument)

• "34.90" 34.9

• "86abc" 86

• "\$24.95" 0

• "3,789" 3

• "" 0

• "x29" 0

• "47%" 47

• "Geraldine" 0

ToString Method Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• This is a Method that will convert any variable to a string, as inDim number As Integer = 123 lblNumber.Text = number.ToString

Option Strict On Be Manipulated, Used to Manipulate Other Information, or Remembered for Later Use

• Placed at the very top of the code window this will prevent Visual Basic .NET from performing implicit data type conversion

• The code must perform all conversions using Val or ToString

Visual Basic .NET Provides Several Operators for Performing Mathematical Operations

You May Also Use Parentheses to Group Operations and Build More Complex Mathematical Statements

### Performing Calculationsand Working With Numbers

The Arithmetic Operators Mathematical Operations

• Visual Basic .NET provides operators for the common arithmetic operations:

• Subtraction -

• Multiplication *

• Division /

• Exponentiation ^

• Examples of use:

• total = price + tax

• area = length * width

• average = total / items

• salePrice = retail / 2

• cube = side ^ 3

Special Integer Division Operator Mathematical Operations

• The backslash (\) is used as an integer division operator

• The result is always an integer, created by doing the division and then discarding any remainder

• Any floating-point operand is first rounded to the nearest integer

Special Modulo (MOD) Operator Mathematical Operations

• This operator follows the same basic rules as the backslash operator, but yields the remainder after the division

• \ operator yields an integer result of division

• MOD operator yields the integer remainder (after division using the \ operator)

Arithmetic Operator Precedence Mathematical Operations

• Which operations are done first -- precedence tells us -- highest to lowest:

• Exponentiation (^)

• Multiplicative (* and /)

• Integer Division (\)

• Modulus (MOD)

• When two operators with the same precedence share an operand, the operator on the left works first, then the operator on the right

Arithmetic Operator Precedence, II Mathematical Operations

• Grouping with parentheses () forces the expression within those parentheses to be evaluated before others

• Roughly speaking, the order of evaluation in Visual Basic .NET is similar to that used in algebra classes (parenthesized expressions first, then exponentiation, then multiplicative operators, then the additive operators)

Combined Assignment Operators Mathematical Operations

• Frequently program assignment statements are similar to:number = number - 5

• That is, modify a variable with one arithmetic operator and store the result back into the same variable

• There are special assignment operators to enhance this usage:

• += add a value to the variable

• -= subtract a value from the variable

• *= multiple the variable by some value

• /= divide the variable by some value

• \= integer divide the variable by some value

• &= concatenate the variable with some value

Cbool Mathematical Operations

Cbyte

Cchar

Cdate

CDbl

CDec

Cint

CLng

Cobj

Cshort

CSng

CStr

More C (Convert) Functions

Named Constants, I Mathematical Operations

• Whenever a program needs to use a constant (e.g., the local sales tax percentage) it is a good idea to give it a variable name

• However, a variable does not necessarily have the same value throughout the program as an assignment statement can change the value

• Visual Basic .NET provides for a variable whose value, once established in the declaration, cannot be modified afterwards:Const salesTax As Single = 0.06