abstract - college of business | university of nevada,...

25
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

Upload: truongnga

Post on 26-Mar-2018

216 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

IS 350 LAB 3STRING AND NUMERIC DATA – GETTING INPUT AND OUTPUTAND AN INTRODUCTION TO DEBUGGINGAbstractIn 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.

Page 2: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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 ControlThe 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:

Page 3: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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 PropertiesbtnCalculate Button Text=CalculatebtnClear Button Text=ClearbtnExit Button Text=ExitlblPromptInitialValue Label Text=InitialValuelblPromptTermYears Label Text=Term (Years)lblPromptInterestRate Label Text= Annual Interest RatelblPromptFutureValue Label Text=Future ValuelblPromptGainOnInvestment Label Text=Gain On InvestmenttxtInitialValue TextBox TextAlign=RighttxtYearlyTerm TextBox TextAlign=RighttxtAnnnualInnterestRate TextBox TextAlign=RightlblFutureValue Label TextAlign=RightlblGain 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 VariableMost applications must store data as the program runs. That data is stored in variables. Variables can be categorized in different ways.

Page 4: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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.

Public Class Form1

Private CallCounter As Integer = 0

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) _ Handles btnCalculate.Click CallCounter = CallCounter + 1 End Sub

End Class Form1

The statement immediately after the Class declaration declares a module-level variable. o Module-level variables are declared inside of a Class block but outside of a procedure. o 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.

Page 5: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

o 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.

Public Class Form1

Private CallCounter As Integer = 0

Private Sub btnCalculate_Click(sender As Object, e As EventArgs) _ Handles btnCalculate.Click CallCounter = CallCounter + 1 End Sub

End Class Form1

3. 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

Page 6: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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.

The Call Stack window is used to examine the procedures that have been called as well as the order in which they were called.

The Locals window 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:

Page 7: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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:

Page 8: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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.

Page 9: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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.

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.

Michael Ekedahl, 04/02/16,
TODO CHANGE FIGUre
Page 10: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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.

Page 11: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

2. Remove the breakpoints by clicking in the left margin of the Code Editor. The maroon circle should disappear.

3. Click View, Output to display the Output window.

4. 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 TypesAll 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:

Page 12: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

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.

Page 13: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

Declaring VariablesA variable represents an 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:

A variable has a lifetime, which is the period of time that a variable exists, during which memory is allocated to store the variable.

o The lifetime of a module-level variable is the time that the module is loaded and running.

o The lifetime of a local variable is the period of time that the procedure is running.

The scope of a variable refers to which classes and procedures can use (reference) the variable.

o The scope of a module-level variable is the class (form) containing the declaration if the Private access modifier is used to declare the variable.

o The scope of a local variable is the procedure containing the declaration.

Accessibility controls how a variable can be used by other classes and modules. Access modifiers are discussed in detail in subsequent labs when multiple forms are presented. The keywords Public and Private are considered access modifiers.

Local variables are declared with the Dim keyword as follows:

[Dim] varName As type [ = initexpr]

The Dim keyword declares a local variable. A local variable must be declared inside of a procedure.

varName contains the name of the variable (identifier)

The As type clause defines the data type of the variable.

The optional initexpr clause initializes the variable to a value. Numeric variables are automatically initialized to 0.

The following statement showd how to declare a local variable:

Dim Count As Integer

Dim Total As Double

Page 14: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

The first of the above statement declares a variable named Count having a data type of Integer. The second declares a variable named Total having a data type of Double.

Module-level variables can be declared with the Private keyword. Module-level variables are declared inside of a class but outside of a procedure block.

There is a special type of variable called a constant. A constant is just a variable whose value never changes. The constant is declared with the Const keyword as the following statement shows:

Private Const MONTHS_PER_YEAR As Integer = 12

The preceding statement declares a constant named MONTHS_PER_YEAR. One common naming convention is to use all capital letters for constants.

The above constant has a data type of Integer.

The constant’s value is initialized to 12. Constants must be initialized when they are declared.

HANDS-ON STEP: Declaring variables:

In this part of the lab, you will declare a module-level variable and the button’s Click event handlers.

1. Activate the Code Editor for the main form, and enter the following declaration. Make sure that these declarations appear inside of the Form class.

Public Class frmMain

Private Const MONTHS_PER_YEAR As Integer = 12

2. Create the following declaration in the procedure named btnCalculate_Click. Make sure to declare the variables inside of the procedure.

Dim AnnualInterestRate As Double Dim MonthlyInterestRate As Double Dim InitialValue As Double Dim YearlyTerm As Integer Dim MonthlyTerm As Integer Dim FutureValue As Double Dim GainOnInvestment As Double

All of the above variables are local variables. The values are implicitly initialized to 0. All numeric data types are implicitly initialized to zero.

Converting String Data to a Numeric FormBefore you can perform numeric operations on a variable, textual data must be converted into numeric data. That’s the purpose of the methods of the System.Convert class. Each member of the System.Convert class accepts one argument – the string to be converted. Each method returns the converted numeric value.

Page 15: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

System.Convert.ToInt32 converts a string to an integer.

System.Convert.ToDouble converts a string to a double precision number.

System.Convert.ToDateTime converts a string to a DateTime data type.

Note that the System.Convert class supports other methods to convert data to other data types. Those methods will be discussed as they are used.

The following code segment shows an example that converts string data into numeric data and store that numeric data in variables having the corresponding numeric data type.

InitialValue = System.Convert.ToDouble(txtInitialValue.Text)

The preceding statement converts the string stored in the Text property of the TextBox named txtInitialValue to a double precision value and stores the result in the variable named InitialValue.

Note that if the value cannot be converted, an exception (error) will be thrown.

HANDS-ON STEP: Converting String data to numeric data and storing values in variables

1. In the procedure named btnCalculate_Click, enter the following statements immediately after the variable declarations.

InitialValue = ToDouble(txtInitialValue.Text) YearlyTerm = ToInt32(txtYearlyTerm.Text)

2. Run the program. In the initial value TextBox, enter the value 123XXX. Click the Calculate button. As you can see, and exception will be thrown because the value cannot be converted to number. You will learn how to correct this problem in subsequent labs.

3. Using the techniques discussed previously, set a breakpoint on each of the above statements. Run the program and enter valid numbers into each of the text boxes. View the values stored in the two numeric varaibles.

4. End the program.

Strict Type Checking and Type ConversionWhen you write arithmetic expressions, a problem can arise called numeric overflow. To illustrate, look at the following statements:

Dim SmallValue As Short = 2500Dim ResultValue As ShortResultValue = SmallValue * SmallValue

The last of the preceding statements will cause a run-time exception to occur because the result of 2500 * 2500 cannot be stored in a variable of type Short. The largest number that can be stored in a short is

Page 16: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

32,767. The solution to the above problem is to use a data type that can store larger numbers. Use The Integer or Long data type.

Strict Type CheckingThe Option Strict statement enables or disables strict type checking. The Option Strict statement must appear at the beginning of a module file, although whitespace or comments can precede it.

Option Strict OnOption Strict Off

If strict type checking is enabled, then less restrictive types will not be implicitly converted to more restrictive type. For example, when strict type checking is enabled, the following statement will cause an error because an Integer is more restrictive that a floating-point number.

Dim Size As Integer = 123.45

Writing Arithmetic ExpressionsArithmetic expressions work the same way as they when writing algebraic expressions. A statement using an arithmetic expression is made up of a left side and a right side. An equals sign separates the left and right side of the expression. The expression in the right side is evaluated and stored in the variable on the right side. The following code segment shows a simple arithmetic expression

Dim Numerator As Double = 10Dim Denominator As Double = 5Dim Result As DoubleResult = Numerator / Denominator * 100

Page 17: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

The assignment statement (shown in bold) first performs a division operation using the values (10 / 5) stored in the variables Numerator and Denominator, multiplies the intermediate result (2) by the literal value 100, and stores the result (200) in the variable Result. Because the division and multiplication operators have the same precedence, the expression is evaluated from left to right, and the operators are evaluated in the order that they appear.

HANDS-ON STEP: Performing arithmetic expressions to calculate the future value of an investment:

In the following steps you will write the arithmetic statement to calculate the future value of an investment.

1. In the btnCalculate_Click event handler, enter the following code, shown in bold, after the code that you have already written:

AnnualInterestRate = ToDouble(txtAnnualInterestRate.Text) / 100 MonthlyInterestRate = AnnualInterestRate / MONTHS_PER_YEAR YearlyTerm = ToDouble(txtYearlyTerm.Text) MonthlyTerm = YearlyTerm * MONTHS_PER_YEAR

The first of the above statements converts the value (Text) stored in the TextBox named txtAnnualInterestRate to the Double data type. That value is divided by the literal value 100. Thus, if you entered 10.00 in the TextBox, then the value stored in the variable AnnualInterestRate will be 0.10.

The next statement divides the AnnualInterestRate by 12 (stored in the constant MONTHS_PER_YEAR).

The next statement converts the value txtYearlyTerm.Text to a Double and stores the result in the variable YearlyTerm.

The final statement converts the annual term to a monthly term so that loan term is expressed in months, rather than years.

Referencing a Namespace and Calling the FV Method of the Microsoft.VisualBasic.Financial ClassVisual Basic supports a class named Financial that belongs to the Microsoft.VisualBasic namespace as follows:

result = FV(Rate, NPer [, Pmt ] [, PV ][, Due ])

The Rate argument stores the interest rate per period. The value should be expressed as a decimal. That is, a 7% interest rate is represented at 0.07.

The NPer (number of periods) argument stores the number of time periods the investment is held. If regular payments are made, they are identified by Pmt payment). To compute the

Page 18: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

future value of a fixed amount, which does not involve regular payments, the value of Pmt would be 0. A regular payment is equivalent to making a deposit into an investment account each period.

The optional PV (present value) argument contains the initial amount of the investment. If the initial investment value is 0, the argument can be omitted.

The optional Due argument describes when payments are made.

The FV (future value) method returns the future value of an investment and stores the value in result.

HANDS-ON STEP: Calculating the future value of an investment

In this next sequence of steps, you will write the code to calculate the future value of an investment:

1. Enter the following code immediately after the code that you just wrote:

FutureValue = FV(MonthlyInterestRate, MonthlyTerm, 0, _ InitialValue) FutureValue = System.Math.Abs(FutureValue) GainOnInvestment = FutureValue - InitialValue

The first of the preceding statements calculates the future value of an investment and stores the result in the variable named FutureValue.

Because the FV method returns a negative number, the System.Math.Abs() method accepts one argument, a number and returns the absolute value of the that number. Thus, the statement converts the value of the variable FutureValue to a positive value.

The final statement subtracts the variable InitialValue from the variable FutureValue. The result is stored in the variable GainOnInvestment.

Displaying and Formatting ResultsOnce you have performed all of the calculations, the output from those calculations need to be converted back to a string form, and displayed to the user. All numeric data types (and all data types for that matter) support a method named ToString() that converts the data to a string.

Page 19: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

lblFutureValue.Text = FutureValue.ToString("C") lblGain.Text = GainOnInvestment.ToString("C")

HANDS-ON STEPS: To display the result of calculations

1. Enter the following statements at the end of the event handler to format and display the output. These statements form the output as a currency value (with a leading dollar sign and formatted to two decimal places.

lblFutureValue.Text = FutureValue.ToString("C") lblGain.Text = GainOnInvestment.ToString("C")

2. Remove the breakpoints that you previously created, if necessary.

3. Run the program. Enter data of your choosing to calculate the future value of an investment.

Page 20: Abstract - College of Business | University of Nevada, Renobusiness.unr.edu/.../IS350LabNumericData.docx · Web viewA local variable’s scope is the procedure containing the declaration

Try it on your ownIn the preceding sections, you created an application that would calculate the future value of an annuity. In this section, you will calculate the present value of an annuity. Instead of using the FV method, you call the PV method having the following arguments.

Refer to the following help page for more information.

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.financial.pv(v=vs.110).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-1

Modify the user interface so that contains the appropriate input and output values. They are very similar. Modify the code for the calculate function so that it calculates the present value of an annuity. Again, this code is very similar to the code that you just wrote.

As a final exercise, you will calculate the payment on a loan. To do this, you will need to use the PMT function. The following figure shows the syntax of the PMT function.

Refer to the following help page for more information.

https://msdn.microsoft.com/en-us/library/microsoft.visualbasic.financial.pmt(v=vs.110).aspx