IS 350 LAB 3
STRING AND NUMERIC DATA – GETTING INPUT AND OUTPUT
AND AN INTRODUCTION TO DEBUGGING

Abstract

In this lab, you will work with numeric data and learn how to do the following:

  • Get input from the user via the TextBox control.
  • Declare and store data into variables.
  • Convert textual data entered by the user into numeric values using methods of the System.Convert class.
  • Use arithmetic operators to perform calculations on input.
  • Call a method.
  • Convert output, stored in variables, back to a string representation and display those values to a user.
  • Throughout this lab, you will also learn how to debug the applications that you write. Debugging is an integral topic of this lab. I STRONGLY SUGGEST that you practice using these tools. They will benefit you throughout the course.

Key Terms

  • Constant: A constant stores a value that cannot be changed as a program runs.
  • Exception: Exceptions are errors that occur because a statement tries to perform an impossible action, such as trying to divide a number by zero, or reading a file that does not exist.
  • Identifier: The name given to a variable or procedure. A identifier must begin with a letter followed by letters or digits. Do not use special characters other than the underscore (_) character.
  • Local variable: A variable declared inside of a procedure block. A local variable’s scope is the procedure containing the declaration. The variable’s lifetime is while the procedure executes.
  • Module-level variable: A variable declared outside of a procedure block but inside a Class block. The module-level variable’s scope is the class containing the declaration. The lifetime is while the class instance exists.
  • Operator: An operator is a special symbol (+, -, *, /…) that performs an operation on one or two operands. Operators are classified into different types, in this lab, you will work with arithmetic operators.
  • Operand: An operand is the part of a computer instruction that specifies data that is to be operating on or manipulated and, by extension, the data itself. Basically, a computer instruction describes an operation (add, subtract, and so forth) and the operand or operands on which the operation is to be performed.
  • Reference type: A reference type is a category of variable there the variable does not store data but instead stores a memory address. That memory address, in turn, contains data. All classes are reference types.
  • Type conversion: The process of converting data from one type to another.
  • Value type: A value type is a category of variable where the data is stored directly in the memory allocated for the variable. The primitive Visual Basic data types are all value types. Structures are also value types.
  • Variable: A variable stores data. It has a data type, such as Integer or Color. The data stored in a variable is based on its data type.

Working with the TextBox Control

The TextBox control operates similar to the Label control in that it displays textual values. However, the user can enter values into a TextBox. In this lab, you will work with the following text box properties:

  • The read/write Text property stores the text that appears in the visible region of the control instance. The property can be set at design-time or read and written at run time.
  • The TextAlign property is used to define how the text will be aligned within the visible region of the control instance.
  • Like other visible controls, the TextBox has a ForeColor and BackColor property.

HANDS-ON STEP: Creating Text Boxes and setting their properties:

  1. In this part of the lab, you will create the user interface for the form. The process is the same as the process you saw in the first lab. The following figure shows the form’s user interface. Again, don’t worry if you’re your user interface does not match exactly the one shown in the following figure:

  2. Create the buttons along the left side of the form. Create the Label prompts. Create the TextBox control instances along the right side of the form. Name the properties and values as follows so that the code you write will correspond to the steps in this lab.

Control name / Type / Properties
btnCalculate / Button / Text=Calculate
btnClear / Button / Text=Clear
btnExit / Button / Text=Exit
lblPromptInitialValue / Label / Text=InitialValue
lblPromptTermYears / Label / Text=Term (Years)
lblPromptInterestRate / Label / Text= Annual Interest Rate
lblPromptFutureValue / Label / Text=Future Value
lblPromptGainOnInvestment / Label / Text=Gain On Investment
txtInitialValue / TextBox / TextAlign=Right
txtYearlyTerm / TextBox / TextAlign=Right
txtAnnnualInnterestRate / TextBox / TextAlign=Right
lblFutureValue / Label / TextAlign=Right
lblGain / Label / TextAlign=Right

HANDS-ON STEP: Creating a user interface

In the following steps, you will create the user interface for this application.

  1. Create a new project named NumericDataLab.
  2. Create the control instances on the main form and name them accordingly based on the above table. It is important to give each control instance the correct name for the Name property for the code you write to work correctly.

Declaring a Variable

Most applications must store data as the program runs. That data is stored in variables. Variables can be categorized in different ways.

  • Local variables are declared inside a procedure. A local variable is created when the procedure is called and destroyed when the procedure exists. A local variable can only be referenced (used) by the procedure containing the local variable declaration.
  • Module-level (class) variables are declared inside of a class (form) but outside of a procedure. Module-level variables are created when the class instance is created, and exist while the class instance (from) exists. Module-level variables can be referenced by all of the procedures in a form.

Variables have a data type that depicts the kind of data that a variable can store. The following table summarizes the .NET primitive data types. These data types are the same from one Visual Studio language to the next.

To illustrate, examine the following code segment that declares a module-level Integer variable. The statements in the event handler increment the variable’s value by one. Arithmetic expressions will be discussed further later in the lab.

PublicClassForm1

Private CallCounter AsInteger = 0

PrivateSub btnCalculate_Click(sender AsObject, e AsEventArgs) _
Handles btnCalculate.Click

CallCounter = CallCounter + 1

EndSub

EndClassForm1

  • The statement immediately after the Class declaration declares a module-level variable.
  • Module-level variables are declared inside of a Class block but outside of a procedure.
  • The Private keyword is called an access modifier. Variables (and procedures) declared with the Private access modifier can be used by all procedures in the current class. They cannot, however, be referenced from outside of the class.
  • The variable has a data type of Integer so it can store only whole numbers. The variable is initialized to 0.
  • The statements in the procedure increment’s the variable’s value by one.

HANDS-ON STEP: Declaring a variable and implementing a counter

  1. Create the Click event handler for the button named btnCalculate. Again, to create a button’s Click event handler, double-click the button in the Windows Forms Designer. Or select the object in the Properties window. Activate Event mode. Double click the desired event.
  2. Modify the code for form so that it looks like the following. Make sure to declare the variable and write the statement to increment the variable’s value.

PublicClassForm1

Private CallCounter AsInteger = 0

PrivateSub btnCalculate_Click(sender AsObject, e AsEventArgs) _
Handles btnCalculate.Click

CallCounter = CallCounter + 1

EndSub

EndClassForm1

  1. Compile the program and to make sure that there are no syntax errors.

Introduction to Program Debugging and Exception Handling.

As you write programs, you will likely make mistakes. The mistakes that you make are categorized into three types:

  • Syntax errors are those errors that violate the rules of a programming language. You saw how to make and correct a syntax error in the first lab.
  • Run-time errors happen as a program executes. When a run-time error occurs, an exception is said to be thrown. Exceptions can be thrown for various reasons including trying to store too large or small a number in a variable.
  • Logic errors produce an incorrect result, but may or may not result in a run-time error.

Visual Studio supplies several tools that help you to debug programs. The following list describes some of these tools (windows):

  • The Breakpoints window is used to select the executable statements in an application where Visual Studio will suspend execution. After execution is suspended, it is common to examine the values of variables in order to determine the cause of a particular error. In addition, the Code Editor and the buttons on the Debug toolbar can be used to execute statements one at a time.
  • In the Immediate window, expressions can be entered that display the values of variables and object properties. It is also possible to call procedures using the Immediate window.
  • Watch windows are used to examine the values of variables and expressions.
  • TheCall Stack window is used to examine the procedures that have been called as well as the order in which they were called.
  • The Localswindow is used to examine the values of local variables, the properties of a form and its control instances, and the variables declared in the form.

Note that there are additional debugging windows that are beyond the scope of this lab.

HANDS-ON STEP: Setting breakpoints

In the following sequence of steps, you will work with selected debugging windows.

  • You will use the Code Editor to set program breakpoints. Just before the statement containing the breakpoint executes, execution is suspended and Visual Studio enters break mode.
  • You will use one of the Watch windows to examine the value of objects and variables.
  • You will use the Immediate window to execute expressions.

You will also intentionally make mistakes so as to better see how to utilize the debugging window.

  1. Make sure that the Code Editor is active for the form. You should have already created the event handlers and the following code. (Your line numbers might vary) In the left margin, click on the End Sub statement. A maroon circle will appear in the left margin and the statement will be highlighted.

  2. You can also view breakpoints in the Breakpoints window. Click Debug, Windows, Breakpoints to view the Breakpoints window shown in the following figure:

    The preceding figure shows one breakpoint set on line 5. Your line number might differ. The check box in the first column indicates that the breakpoint is enabled. Conditional breakpoints and Hit Count breakpoints will be discussed later.
  3. Now run the program by pressing F5 or clicking Debug, Start Debugging. Click the Calculate button. The breakpoint will be hit thereby suspending execution of your program. You will see the statement with the breakpoint highlighted as shown in the following figure:

  4. Note that when execution is suspended, Visual Studio enters Break mode as the following menu items show:

    The menu shows the Continue button. If you click Continue execution will resume. The pause button is disabled because program execution is suspended. If you click the Stop button, then execution will end. The other debugging buttons will be discussed as you progress through this lab.

HANDS-ON STEP: Interrogating the values of objects and variables

Now that execution is suspended, you can look at the value of variables and other objects, which you will do next. In this section, you will use two windows to see “what your program is doing”. The first is the Watch window and the second is the Immediate window. There are four Watch windows and each works exactly the same way. There are multiple Watch windows so that you can repeatedly watch different parts of a program.

  1. Click Debug, Window, Watch 1. The Window should be blank initially. Recall that the variable named CallCounter is declared as a module-level variable and so is persistent while the program runs and the form is loaded.
  2. In the Name column, enter the value CallCounter. Press Enter. The variable’s value should appear as shown in the following figure:

  3. You can also view the properties of objects. Assuming that the button on the form is named btnCalculate, enter that variable (button) name in the Name column. As you can see in the following figure, an arrow appears indicating that you can expand the object and view its properties.

  4. Click the arrow in the first column to expand the object. As you can see, all of the object’s properties are displayed. Note that some properties can be expanded. Expand the BackColor property, which has been previously discussed. When you do, you see all of the properties related to the color.

  5. Now you will look at another window called the Immediate window. This window provides a way for you to enter expressions and have .NET to evaluate them and display the results. On the menu bar, click View, Immediate to display the Immediate window. By default, the Immediate window is docked along the bottom of the main development environment window.

  6. Any valid Visual Basic expression can be entered in the Immediate window. A question mark precedes the expression. Enter the expression shown in the following figure to display the Text property of the button named btnCalculcate. The expression is evaluated and the result is displayed[ME1].

  7. Enter ?btnDemo1.Color. As you can see, an error appears indicating that the Color property is not supported by the Button control. Correct the error by entering ?btnDemo1.BackColor. As you can see, the values of the BackColor structure are displayed.

You will work more with the debugging windows in this and subsequent labs so as to understand common mistakes and how to correct them.

Using Debug.WriteLine()

.NET supports an object named Debug that belongs to the System.Diagnostics namespace. The WriteLine() method allows you to write a string to the Output window so as to trace the execution of a program as shown in the following statement:

Debug.WriteLine(CallCounter.ToString())

The preceding statement write the value of the variable CallCounter (converted to a String) to the output window.

HANDS-ON STEP: Interrogating the values of objects and variables

  1. Modify the procedures that you just wrote so that they include the following calls to the Debug.WriteLine() method.
  1. Remove the breakpoints by clicking in the left margin of the Code Editor. The maroon circle should disappear.
  2. Click View, Output to display the Output window.
  3. Run the program. Click the two buttons. As you do, the output from the Debug.WriteLine() method appears in the Output window as the following figure shows:

    As you can see, the variable CallCounter is being incremented by 1 each time a button is clicked.

Understanding the Difference between Reference Types and Value Types

All variables can be categorized as either value types or reference types. You will explore each, in turn.

Value types store data in the memory allocated to the variable. To illustrate, examine the following figure:

As shown in the above figure, The Byte data type stores data in one byte. The Short data type stores data in two bytes.

.NET provides a method that will determine the size (in bytes) of any value type. The System.Runtime.InteropServices.Marshal,SizeOf() method accepts one argument, a value type variable (primary type or structure). Take a look at the following statements:

Debug.WriteLine(Runtime.InteropServices.Marshal.SizeOf(Day))

Debug.WriteLine(Runtime.InteropServices.Marshal.SizeOf(Month))

Debug.WriteLine(Runtime.InteropServices.Marshal.SizeOf(Year))

Debug.WriteLine(Runtime.InteropServices.Marshal.SizeOf(btnDemo3.BackColor))

If you were to run this code, you would see that the size of Day is one byte, the size of Month is one byte, and the size of Year is two bytes. The last statement takes a bit more explanation. The size of the BackColor property is 24 bytes. If you add the size of all of the property members, you end up with 24 bytes.

Reference types work much differently. Instead of storing data, the memory allocated to a variable stores another memory address. This memory address stores the data for the actual reference object.

Note that the memory allocated to store a reference type variable will be either 32 bits or 64 bits depending on whether you are using a 32 bit or 64 bit version.

Declaring Variables

A variable representsan amount of memory, allocated by the system that stores data while an application runs. A variable has a name (identifier) by which the variable is referenced, just as every property or object has a name. The process of creating a variable is known as declaring a variable. When a variable is declared, that variable is given a data type and a name (identifier). The rules for naming variables are the same as those for naming all identifiers.

  • Identifier names must begin with a letter or the underscore character.
  • The remaining characters can be letters, digits, or the underscore character.

All variables have the following three characteristics: