Working with Visual Basic Operators


Working with Visual Basic Operators

A formula is a statement that combines numbers, variables, operators, and keywords to create a new value. Visual Basic contains several language elements designed for use in formulas. In this section, you'll practice working with mathematical operators, the symbols used to tie together the parts of a formula. With a few exceptions, the mathematical symbols you'll use are the ones you use in everyday life, and their operations are fairly intuitive. You'll see each operator demonstrated in the following exercises.

Visual Basic includes the following operators:

Operator

Description

+

Addition

Subtraction

*

Multiplication

/

Division

\

Integer (whole number) division

Mod

Remainder division

^

Exponentiation (raising to a power)

&

String concatenation (combination)

Basic Math: The +, –, *, and / Operators

The operators for addition, subtraction, multiplication, and division are pretty straightforward and can be used in any formula where numbers or numeric variables are used. The following exercise demonstrates how you can use them in a program.

Work with basic operators

  1. On the File menu, click Open Project.

  2. Open the Basic Math project in the c:\vb05sbs\chap05\basic math folder.

  3. If the project's form isn't visible, click Form1.vb in Solution Explorer, and then click the View Designer button.

    The Basic Math form appears in the Designer. The Basic Math program demonstrates how the addition, subtraction, multiplication, and division operators work with numbers you type. It also demonstrates how you can use text box, radio button, and button objects to process user input in a program.

  4. Click the Start Debugging button on the Standard toolbar.

    The Basic Math program runs in the IDE. The program displays two text boxes in which you enter numeric values, a group of operator radio buttons, a box that displays results, and two button objects (Calculate and Quit).

  5. Type 100 in the Variable 1 text box, and then press Tab.

    The insertion point, or focus, moves to the second text box.

  6. Type 17 in the Variable 2 text box.

    You can now apply any of the mathematical operators to the values in the text boxes.

  7. Click the Addition radio button, and then click the Calculate button.

    The operator is applied to the two values, and the number 117 appears in the Result box, as shown below.

    graphic

  8. Practice using the subtraction, multiplication, and division operators with the two numbers in the variable boxes. (Click Calculate to calculate each formula.)

    The results appear in the Result box. Feel free to experiment with different numbers in the variable text boxes. (Try a few numbers with decimal points if you like.) I used the Double data type to declare the variables, so you can use very large numbers.

    Now try the following test to see what happens:

  9. Type 100 in the Variable 1 text box, type 0 in the Variable 2 text box, click the Division radio button, and then click Calculate.

    Dividing by zero is not allowed in mathematical calculations, because it produces an infinite result. But Visual Basic is able to handle this calculation and displays a value of Infinity in the Result text box. Being able to handle some divide-by-zero conditions is a feature that Visual Basic 2005 automatically provides.

  10. When you've finished contemplating this and other tests, click the Quit button.

    The program stops, and the development environment returns.

Now take a look at the program code to see how the results were calculated. Basic Math uses a few of the standard input controls you experimented with in Chapter 3 and an event procedure that uses variables and operators to process the simple mathematical formulas. The program declares its variables at the top of the form so that they can be used in all of the Form1 event procedures.

Examine the Basic Math program code

  1. Double-click the Calculate button on the form.

    The Code Editor displays the Button1_Click event procedure. At the top of the form's code, you'll see the following statement, which declares two variables of type Double:

    'Declare FirstNum and SecondNum variables  Dim FirstNum, SecondNum As Double

    I used the Double type because I wanted a large, general purpose variable type that could handle many different numbers—integers, numbers with decimal points, very big numbers, small numbers, and so on. The variables are declared on the same line by using the shortcut notation. Both FirstNum and SecondNum are of type Double, and are used to hold the values input in the first and second text boxes, respectively.

  2. Scroll down in the Code Editor to see the contents of the Button1_Click event procedure.

    Your screen looks similar to this:

    graphic

    The first two statements in the event procedure transfer data entered in the text box objects into the FirstNum and SecondNum variables.

    'Assign text box values to variables  FirstNum = TextBox1.Text  SecondNum = TextBox2.Text

    The TextBox control handles the transfer with the Text property—a property that accepts text entered by the user and makes it available for use in the program. I'll make frequent use of the TextBox control in this book. When it's set to multiline and resized, it can display many lines of text—even a whole file!

    After the text box values are assigned to the variables, the event procedure determines which radio button has been checked, calculates the mathematical formula, and displays the result in a third text box. The first radio button test looks like this:

    'Determine checked button and calculate  If RadioButton1.Checked = True Then      TextBox3.Text = FirstNum + SecondNum  End If

    Remember from Chapter 3 that only one radio button object in a group box object can be selected at once. You can tell whether a radio button has been selected by evaluating the Checked property. If it's True, the button has been selected. If the Checked property is False, the button has not been selected. After this simple test, you're ready to compute the result and display it in the third text box object. That's all there is to using basic mathematical operators. (You'll learn more about the syntax of If...Then tests in Chapter 6, “Using Decision Structures.”)

You're done using the Basic Math program.

New Shortcut Operators

An interesting feature of Visual Basic 2002, 2003, and 2005 is that you can use shortcut operators for mathematical and string operations that involve changing the value of an existing variable. For example, if you combine the + symbol with the = symbol, you can add to a variable without repeating the variable name twice in the formula. Thus, you can write the formula X = X + 6 by using the syntax X += 6. The following table shows examples of these shortcut operators.

Operation

Long-form syntax

Shortcut syntax

Addition (+)

X = X + 6

X += 6

Subtraction (-)

X = X – 6

X -= 6

Multiplication (*)

X = X * 6

X *= 6

Division (/)

X = X / 6

X /= 6

Integer division (\)

X = X \ 6

X \= 6

Exponentiation (^)

X = X ^ 6

X ^= 6

String concatenation (&)

X = X & "ABC"

X &= "ABC"

Using Advanced Operators: \, Mod, ^, and &

In addition to the four basic mathematical operators, Visual Basic includes four advanced operators, which perform integer division (\), remainder division (Mod), exponentiation (^), and string concatenation (&). These operators are useful in special-purpose mathematical formulas and text processing applications. The following utility (a slight modification of the Basic Math program) shows how you can use each of these operators in a program.

Work with advanced operators

  1. On the File menu, click Open Project.

    The Open Project dialog box appears.

  2. Open the Advanced Math project in the c:\vb05sbs\chap05\advanced math folder.

  3. If the project's form isn't visible, click Form1.vb in Solution Explorer, and then click the View Designer button.

    The Advanced Math form appears in the Designer. The Advanced Math program is identical to the Basic Math program, with the exception of the operators shown in the radio buttons and in the program.

  4. Click the Start Debugging button on the Standard toolbar.

    The program displays two text boxes in which you enter numeric values, a group of operator radio buttons, a text box that displays results, and two buttons.

  5. Type 9 in the Variable 1 text box, and then press Tab.

  6. Type 2 in the Variable 2 text box.

    You can now apply any of the advanced operators to the values in the text boxes.

  7. Click the Integer Division radio button, and then click the Calculate button.

    The operator is applied to the two values, and the number 4 appears in the Result box, as shown here:

    graphic

    Integer division produces only the whole number result of the division operation. Although 9 divided by 2 equals 4.5, the integer division operation returns only the first part, an integer (the whole number 4). You might find this result useful if you're working with quantities that can't easily be divided into fractional components, such as the number of adults who can fit in a car.

  8. Click the Remainder radio button, and then click the Calculate button.

    The number 1 appears in the Result box. Remainder division (modulus arithmetic) returns the remainder (the part left over) after two numbers are divided. Because 9 divided by 2 equals 4 with a remainder of 1 (2 + 4 + 1 = 9), the result produced by the Mod operator is 1. In addition to adding an early-seventies vibe to your code, the Mod operator can help you track “leftovers” in your calculations, such as the amount of money left over after a financial transaction.

  9. Click the Exponentiation radio button, and then click the Calculate button.

    The number 81 appears in the Result box. The exponentiation operator (^) raises a number to a specified power. For example, 9 ^ 2 equals 92, or 81. In a Visual Basic formula, 92 is written 9 ^ 2.

  10. Click the Concatenation radio button, and then click the Calculate button.

    The number 92 appears in the Result box. The string concatenation operator (&) combines two strings in a formula, but not through addition. The result is a combination of the “9” character and the “2” character. String concatenation can be performed on numeric variables—for example, if you're displaying the inning-by-inning score of a baseball game as they do in old-time score boxes—but concatenation is more commonly performed on string values or variables.

    Because I declared the FirstNum and SecondNum variables as type Double, you can't combine words or letters by using the program code as written. As an example, try the following test, which causes an error and ends the program.

  11. Type birth in the Variable 1 text box, type day in the Variable 2 text box, verify that Concatenation is selected, and then click Calculate.

    Visual Basic is unable to process the text values you entered, so the program stops running, and an error message appears on the screen, as shown here:

    graphic

    This type of error is called a run-time error—an error that surfaces not during the design and compilation of the program, but later, when the program is running and encounters a condition that it doesn't know how to process. If this seems odd, you might imagine that Visual Basic is simply offering you a modern rendition of the robot plea “Does not compute!” from the best science fiction films of the 1950s. The computer-speak message “Conversion from string "birth" to type ‘Double’ is not valid” means that the words you entered in the text boxes (“birth” and “day”) could not be converted, or cast, by Visual Basic to variables of the type Double. Double types can only contain numbers. Period.

    As we shall explore in more detail later, Visual Studio no longer leaves you hanging with this problem, but provides a dialog box with different types of information to help you resolve the run-time error. (Debugging has been a major area of improvement in Visual Studio 2005.) You have learned another important lesson about data types and when not to mix them.

  12. Click the Stop Debugging button on the Standard toolbar to end the program.

    Your program ends and returns you to the development environment.

    NOTE
    In Chapter 8, “Debugging Visual Basic Programs,” you'll learn about debugging mode, which allows you to track down the defects, or bugs, in your program code.

    Now take a look at the program code to see how variables were declared and how the advanced operators were used.

  13. Scroll to the code at the top of the Code Editor.

    You see the following comment and program statement:

    'Declare FirstNum and SecondNum variables  Dim FirstNum, SecondNum As Double

    As you might recall from the previous exercise, FirstNum and SecondNum are the variables that hold numbers coming in from the TextBox1 and TextBox2 objects.

  14. Change the data type from Double to String so that you can properly test how the string concatenation (&) operator works.

  15. Scroll down in the Code Editor to see how the advanced operators are used in the program code.

    You see the following code:

    'Assign text box values to variables  FirstNum = TextBox1.Text  SecondNum = TextBox2.Text    'Determine checked button and calculate  If RadioButton1.Checked = True Then      TextBox3.Text = FirstNum \ SecondNum  End If  If RadioButton2.Checked = True Then      TextBox3.Text = FirstNum Mod SecondNum  End If  If RadioButton3.Checked = True Then      TextBox3.Text = FirstNum ^ SecondNum  End If  If RadioButton4.Checked = True Then      TextBox3.Text = FirstNum & SecondNum  End If

    Like the Basic Math program, this program loads data from the text boxes and places it in the FirstNum and SecondNum variables. The program then checks to see which radio button the user checked and computes the requested formula. In this event procedure, the integer division (\), remainder (Mod), exponentiation (^), and string concatenation (&) operators are used. Now that you've changed the data type of the variables to String, run the program again to see how the & operator works on text.

  16. Click the Start Debugging button.

  17. Type birth in the Variable 1 text box, type day in the Variable 2 text box, click Concatenation, and then click Calculate.

    The program now concatenates the string values and doesn't produce a run-time error, as shown here:

    graphic

  18. Click the Quit button to close the program.

You're finished working with the Advanced Math program.

TIP
Run-time errors are difficult to avoid completely—even the most sophisticated application programs, such as Microsoft Word or Microsoft Excel, sometimes run into error conditions that they can't handle, producing run-time errors, or crashes. Designing your programs to handle many different data types and operating conditions helps you produce solid, or robust, applications. In Chapter 9, “Trapping Errors Using Structured Error Handling,” you'll learn about another helpful tool for preventing run-time error crashes—the structured error handler.



Microsoft Visual Basic 2005 Step by Step
Microsoft Visual Basic 2005 Step by Step (Step by Step (Microsoft))
ISBN: B003E7EV06
EAN: N/A
Year: 2003
Pages: 168

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net