Você está na página 1de 16

VB.

NET LECTURE Lecture 2


Lecture 2 - Fundamentals of VB.Net programs Constants The syntax of constant declarations has not changed in .NET. However, Public constants are now legal in a form (class) module. In VB 6, constants appearing in a form or class module had to be declared with the Private keyword. Constants significantly improve program readability and maintainability. By using a constant in place of a literal value, the developer can clearly see the purpose of the value. Note that constants are evaluated at compile time rather than at run time. Thus, while literal values and arithmetic expressions can be used to initialize the value of a constant, variables cannot be used because the value of a variable does not exist until run time. Examples Const csngPI As Single = 3.14159 This statement declares a constant having a data type of Single and initializes the value to 3.14159 (the value of Pi) Public Const cstrName As String = "Application Name" Private Const cDate As Single = System.DateTime.Today Private Const cVar as Integer = pintValue Using Boolean Data Consider demonstrating Boolean properties like Visible and Enabled. Write code to set these properties at run time. The following statements assume the text box named txtDemo exists: txtDemo.Visible = True txtDemo.Enabled = False Having introduced the Boolean data type, we continue by introducing comparison operators, and how they produce a Boolean result. Note that VB .NET supports the following comparison operators: >, <, >=, <=, =, <>

Note the following about comparison operators: Comparison operators always produce a Boolean result. In an expression, comparison operators are evaluated after arithmetic operators. That is, arithmetic operators have a higher precedence than Comparison operators. Comparison operators are evaluated from left to right. Unlike arithmetic operators, comparison operators all have the same precedence

Lecturer: Mr Ajit Gopee

Page 1 of 16

VB.NET LECTURE
Understanding these expressions sets the stage for their use in an If statement. Private mblnDemo As Boolean In the following statement, 3 is greater than 2 so the result is True. That is, True is stored in the variable mblnDemo. mblnDemo = 3 > 2 ' True

In the following statement, the arithmetic is performed first, and then the greater than operator is applied. We suggest showing the order of evaluation as follows: mblnDemo = 3 + 3 > 2 + 6 mblnDemo = 6 > 8 ' False ' False

The following statement illustrates how more complex arithmetic expressions can be applied. Note that arithmetic operations are performed using the default order of precedence. That is, the multiplication is performed first, and then the addition and subtraction is performed. Finally, the comparison operator is applied. mblnDemo = 6 1 * 2 <= 5 * 5 mblnDemo = 6 2 <= 25 mblnDemo = 4 <= 25 mblnDemo = True Shared members (methods) Standard functions are not available in VB.NET as in VB6. Instead shared methods are used. A shared method is one that can be accessed directly from the class that defines it rather than from an instance of that class. Examples of shared methods of the Math class Abs Absolute value of a number Cos Cosine of an angle Sin Sine of an angle Sqrt Square root of a number Round rounds a number to the specific precision Min returns the largest of 2 numbers Max returns the smallest of 2 numbers Others members are log, log 10, pow, exp etc Examples debug.writeline (math.round(49.78845))-- 50 debug.writeline (math.round(49.78845, 2))-- 49.79 debug.writeline (math.sqrt(20.25))-- 4.5 debug.writeline (math.max(40, 70))-- 70

Lecturer: Mr Ajit Gopee

Page 2 of 16

VB.NET LECTURE
(This one we will try later) Formatting output with Zones Data can be displayed tabulated form in a control such as a list box. The width of the columns can be divided into zones with format string. An example let say you have 4 columns with the following different widths (10, 9, 14 13). VB.NET defines the zones (widths) as a reference to an integer number. That is the first zone is referred to as zone 0, the second zone as 1 etc. The zones are declared in a string as:
Dim mystringzone as string = {0,10} {1,9} {2,14} {3,13}

Example Defining zones

Private Sub btnDisplay_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisplay.Click Dim fmtStr As String = "{0,-10}{1,9}{2,14:N2}{3,13:N2}" Const hrrate As Single = 100.5 Dim hrswork As Single With lstEmployee.Items .Clear() .Add(String.Format(fmtStr, "Employee ID", "Hrswork", "Basic Salary", "Extra Bonus")) hrswork = 200 .Add(String.Format(fmtStr, "1001", hrswork, hrrate * hrswork, hrrate * hrswork * 0.1)) hrswork = 235 .Add(String.Format(fmtStr, "1002", hrswork, hrrate * hrswork, hrrate * hrswork * 0.1)) End With End Sub

The zones can be formatted as follows: {1,10: N0}----- 3452.8789---- 3,453 {1,10: N2}----- 3452.8789---- 3,453.88 {1,10: C1}----- 3452.8789---- $3,453.9 {1,10: P}----- 0.8789---- 87.89%

Lecturer: Mr Ajit Gopee

Page 3 of 16

VB.NET LECTURE
Use of IsNumeric() function for data validation The IsNumeric() function tests whether the value of an expression can be cast as numeric data type. This function returns a Boolean value that can be tested in a conditional expression. Data validation is the process of verifying the data input by the user. If IsNumeric(txtHoursWork) then Some statements and calculations Else MessageBox.Show (You must enter a numeric value, Entry Error) End If Formatting functions There are 3 main FormatPercent().

formatting

functions:

FormatNumber(),

FormatCurrency(),

FormatNumber(-34.6789) FormatNumber(34.6789,1) FormatCurrency(2000) FormatPercent(0.2386847) FormatPercent(0.2386847,1)

----------------

-34.68 34.7 $2,000.00 23.87% 23.9%

Decision Making The following two If statements illustrate a simple Boolean comparison using the Visible property of a TextBox named txtDemo. Note that the ( = True) clause is optional so the following two If statements are equivalent: If txtDemo.Visible = True Then txtDemo.Visible = False End If If txtDemo.Visible Then txtDemo.Visible = False End If The following If statement has the same effect as the preceding two If statements: If Not ( txtDemo.Visible = False ) Then txtDemo.Visible = False End If

Lecturer: Mr Ajit Gopee

Page 4 of 16

VB.NET LECTURE

Numeric values can be used to build the condition as shown in the following statements. The following statement is simplified as literal values are used. If 4 > 7 Then Debug.Writeline("Statement is True") Else Debug.WriteLine("Statement is False") End If The following If statements test whether a date variable is greater than, equal to, or less than the current date. We provide two variations on the same If statement to illustrate different ways of creating the ElseIf and Else parts of the statements.

Private mdatDateValue As Date ' Statements to store a value in mdatDateValue If mdatDateValue > System.DateTime.Today Then Debug.WriteLine("A date in the future.") Else If mdatDateValue = System.DateTime.Today Then Debug.WriteLine("The current date.") Else Debug.WriteLine("A date in the past.") End If If mdatDateValue > System.DateTime.Today Then Debug.WriteLine("A date in the future.") Else If mdatDateValue = System.DateTime.Today Then Debug.WriteLine("The current date.") Else If mdatDateValue < System.DateTime.Today Then Debug.WriteLine("A date in the past.") End If Applied Example Multi-way If statements and nested If statements tend to be very confusing. Here, I describe an example to determine the cost of an insurance policy based upon the following criteria: The insurance rate varies depending on whether a person is a smoker or a nonsmoker. The insurance rate also varies depending a person's age.

Lecturer: Mr Ajit Gopee

Page 5 of 16

VB.NET LECTURE
The following code segment illustrates one possible If statement that will determine an insurance rate based on various criteria. Assume that the variable mblnSmoker defines whether the person smokes or not. The variable mintAge defines the person's age. The variable msngRate stores the rate depending a person's age and whether they smoke or not. The following table illustrates the rate matrix: Smoker 242.55 265.75 292.85 Non-Smoker 142.55 165.75 195.85

Age is 0 to 19

Age is 20 39 Age is greater than or equal to 40 Private mblnSmoker As Boolean Private mintAge As Integer Private msngRate As Single If mblnSmoker Then If mintAge < 20 Then msngRate = 242.55 ElseIf mintAge < 40 Then msngRate = 265.75 Else msngRate = 292.85 End If Else If mintAge < 20 Then msngRate = 142.55 ElseIf mintAge < 40 Then msngRate = 165.75 Else msngRate = 192.85 End If End If

Exercise Testing Smoker Non-Smoker rate matrix Write a VB. NET program that allows the user to enter a choice (smoker or not smoker) and the age from textboxes using the logic mentioned above to display the statistic for the insurance rate. (Please for the time being DO NOT use option buttons).

Lecturer: Mr Ajit Gopee

Page 6 of 16

VB.NET LECTURE
Example 2a - Computing a Mean and Standard Deviation Develop a VB.NET application that allows the user to input a sequence of numbers. When done inputting the numbers, the program should compute the mean of that sequence and the standard deviation. If N numbers are input, with the ith number represented by xi, the formula for the mean ( x ) is:

x = ( xi )/ N
i =1

and to compute the standard deviation (s), take the square root of this equation: s2 = [N xi2 - ( xi )2]/[N(N - 1)]
i =1 i =1 N N

The Greek sigmas in the above equations simply indicate that you add up all the corresponding elements next to the sigma.

Public Class Form1 Inherits System.Windows.Forms.Form Dim NumValues As Short Dim SumX As Single Dim SumX2 As Single Windows Form Designer generated code Private Sub cmdAccept_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAccept.Click Dim Value As Single txtInput.Focus() NumValues = NumValues + 1 lblNumber.Text = CStr(NumValues) 'Get number and sum number and number-squared Value = CSng(txtInput.Text) SumX = SumX + Value SumX2 = SumX2 + Value ^ 2 txtInput.Text = "" End Sub

Lecturer: Mr Ajit Gopee

Page 7 of 16

VB.NET LECTURE

Private Sub cmdCompute_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdCompute.Click Dim Mean As Single Dim StdDev As Single txtInput.Focus() 'Make sure there are at least two values If NumValues < 2 Then Beep() Exit Sub End If Mean = SumX / NumValues lblMean.Text = CStr(Mean) 'Compute standard deviation StdDev = System.Math.Sqrt((NumValues * SumX2 - SumX ^ 2) / (NumValues * (NumValues - 1))) lblStdDev.Text = FormatNumber(CStr(StdDev), 2) End Sub Private Sub cmdNew_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdNew.Click txtInput.Focus() NumValues = 0 lblNumber.Text = "0" txtInput.Text = "" lblMean.Text = "" lblStdDev.Text = "" SumX = 0 SumX2 = 0 End Sub Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Me.Close() End Sub End Class

The Select Case Statement The condition in a Select Case statement must also evaluate to a Boolean value. Just like the condition in an If statement, the condition in a Select Case statement can contain numeric values, date values, and strings. In its simplest form, the Select Case statement contains a test expression having a single value. Each case then tests that the condition contains one of those values. Thus, the text expression and the condition are compared for equality.

Lecturer: Mr Ajit Gopee

Page 8 of 16

VB.NET LECTURE
The following code segment illustrates the simplest form of a Select Case statement. The variable mintValue is tested to determine whether it contains the value 1, 2, 3, or 4. The variable mstrValue is set accordingly. Private mintValue As Integer Private mstrValue As String Select Case mintValue Case 1 mstrValue = "One" Case 2 mstrValue = "Two" Case 3 mstrValue = "Three" Case 4 mstrValue = "Four" End Select In addition to using comparing numeric values, the condition in a Select Case statement can contain string values. Again, the following simple tests for equality but uses strings instead *of numeric values in the condition. The following Select Case statement illustrates the determination of sales tax rates for different states ("CA", "NV", "AZ"):

Private mstrState As String Private msngRate As Single Select Case mstrState Case "CA" msngRate = 0.08 Case "NV" msngRate = 0.07 Case "AZ" msngRate = 0.065 End Select In the preceding two Select Case statements, the test expression contained a single variable, and the simple condition was tested for equality. However, the test expression can be more complex containing an arithmetic expression. The following Select Case statements illustrates how to determine whether a number is odd or even:

Lecturer: Mr Ajit Gopee

Page 9 of 16

VB.NET LECTURE
Dim mintValue As Integer = 5 Select Case mintValue Mod 2 Case 0 Debug.WriteLine("Even") Case 1 Debug.WriteLine("Odd") End Select In addition to using the Select Case statement to compare a single value as shown in the preceding statements, more complex Select Case statements can be written to compare the test expression with a range of values as the following statements illustrate: Private mintAge As Integer Select Case mintAge Case 0 To 20 msngRate = 35 Case 21 To 30 msngRate = 45 Case 31 To 40 msngRate = 50 Case Else msngRate = 60 End Select The preceding Select Case statement illustrates the use of the To keyword to test whether a value is between some range of values. Note to the student that the preceding Select Case statement will only work correctly with integers. If used with floating point numbers, values such as 20.5 will not fall into one of the cases. The following Select Case statement involving relational operators will solve this problem: Private msngAge As Single Select Case msngAge Case Is <= 20 msngRate = 35 Case Is <= 30 msngRate = 45 Case Is <= 40 msngRate = 50 Case Else msngRate = 60 End Select

Lecturer: Mr Ajit Gopee

Page 10 of 16

VB.NET LECTURE
The preceding statement uses logical operators each case. Note that the order of each case is significant. It proceeds from the smallest value to the largest value. Note that once a case matches the test expression, the statements for that case are executed, and then execution continues at the statement following the End Select. Finally, a comma-separated list can appear in a Select Case statement as follows: Select Case mintTest Case 1, 3, 5 ' The value is 1, 3, or 5. Case 2, 4, 6 ' The value is 2, 4, or 6. End Select Logical Operators Note the following about the evaluation of logical operators: Logical operators are applied in an expression after all arithmetic and comparison operations have been performed. Logical operators are evaluated from left to right in the following order. o The Not operator is a unary operator and performs negation. It is evaluated first. o The And operator is applied next. o The Or operator is applied next. o Finally, the Xor operator is applied. As a simple first example, discuss the logical operators using literal values: If 2 > 1 and 3 > 2 Or 4 < 3 then If True And True Or False Then ' The statement is true Moving to the more complex, we use logical operators with more complex expressions as follows: Private mintAge As Integer Private mintNumberOfTickets = 3 If mintAge > 16 And mintAge < 21 And mintNumberOfTickets > 2 Then msngRateMultiplier = 1.1 End If

Lecturer: Mr Ajit Gopee

Page 11 of 16

VB.NET LECTURE
Repetition Statements Here we will introduce repetition structures including Do loops and For loops. The concept of counters and accumulators are also presented in this section. The Do loops: The conditions in a Do loop have the same syntax as the conditions in an If statement. That is, the condition in a Do loop evaluates to a Boolean value and can consist of arithmetic, comparison, and logical operators. The Do While loop executes the statements appearing in the loop while a condition is True. The condition is tested before the statements in the loop execute the first time so it is possible that the statements in a Do While loop will never execute. To Do Until loop executes any statements appearing in the loop until a condition becomes True. Again, the condition is tested before the statements in the loop execute the first time. The Do Loop While and Do Loop Until statements test the condition after the statements in the loop have executed at least once. Thus, the statements in the loop will always execute at least once. The statements in a Do loop form a statement block much like the statement in a one-way if statement form a block. The statements that make up the statement block inside of a Do loop can themselves contain If statements and additional Do loops. Thus, both loops and decision-making statements can be nested. At some point, a condition must occur that causes the loop to terminate. A Counter or accumulator is commonly used in the condition. Consider the following points about counters and accumulators as they apply to repetition statements: A counter is just a variable, typically of type Integer, whose value is incremented or decremented by a constant value, each time through a loop. An accumulator is just a variable, whose value is updated each time through a loop so as to calculate a total.

VB .NET provides a new shortcut syntax variation when working with counters and accumulators similar to those found in C++. The following statements to increment a counter are equivalent: pintCount = pintCount + 1 pintCount += 1

Lecturer: Mr Ajit Gopee

Page 12 of 16

VB.NET LECTURE
Other arithmetic shortcut operators are also supported. The following equivalent statements decrement a counter. In addition, shortcuts also exist for multiplication (*=),division (/=), and integer division (\=). pintCount = pintCount - 1 pintCount -= 1 While the syntax of a loop is usually straightforward for students, the following problems are often encountered. Infinite Loops A loop is written in such a way that the terminal condition never becomes True, so the loop never exits. Remember that infinite loops are often caused by neglecting to increment or decrement a counter. Invalid Initial and Terminal conditions When examining the elements in an array, the student commonly misses the first or last element. Note that arrays will be discussed later. Another possibility is that the student's code tries to reference an array element that does not exist.
Infinite loops are common programming errors and that you can press the Break button on the Debug toolbar to suspend execution. Typically a statement in the infinite loop is highlighted.

There are several ways to write the same Do loop using either the Do Until or Do While variations. For example consider the following equivalent Do loops: Dim pintCount As Integer pintCount = 1 Do Until pintCount > 10 Debug.WriteLine(pintCount) pintCount += 1 Loop Dim pintCount As Integer pintCount = 1 Do While pintCount <= 10 Debug.WriteLine(pintCount) pintCount += 1 Loop The preceding statements print the counting numbers between 1 and 10 using two variations of the Do loop. They are both correct and understandable. The only difference between the two loops is that the condition has been reversed. Which to use is a matter of personal preference.

Lecturer: Mr Ajit Gopee

Page 13 of 16

VB.NET LECTURE
Compare the preceding two loops with the following loop: Dim pintCount As Integer pintCount = 1 Do Until Not pintCount <= 10 Debug.WriteLine pintCount pintCount += 1 Loop The Do loops can contain complex conditions and can be nested. The following statements illustrate a nested Do loop to print a multiplication table. The multiplication table appears thru the number 12. Dim pintOp1 As Integer, pintOp2 As Integer Dim pintResult As Integer Do Until pintOp1 > 12 Do Until pintOp2 > 12 pintResult = pintOp1 * pintOp2 txtOutput.Text = txtOutput.Text & ControlChars.CrLf & _ pintOp1.ToString & " * " & pintOp2.ToString & " = " & _ pintResult.ToString pintOp2 += 1 Loop pintOp2 = 0 pintOp1 += 1 Loop The For Loop The For loop can be used when the number of loop iterations is known in advance. The For loops are commonly used with arrays. The following points can be made of a For loop: Use a For loop when the number of iterations is known in advance. Note that the For loop increments the value of the counter automatically. Remind the student not to change the counter's value with a statement inside the For loop. Otherwise, the counter's value will become corrupted. The optional Step increment clause can be used to change the value by which the counter is incremented or decremented. If the value is negative, then the counter is decremented. The Exit For statement exits for For loop immediately. Statement execution continues at the statement following the Next statement. Note also that the value of the counter is preserved. As a final note, the repetition statements are commonly used with other types of statements such as the If and Select Case decision-making statements. The Do loops can also appear inside of the block of an If statement. These more complex logical structures are not always apparent to the introductory student. Lecturer: Mr Ajit Gopee Page 14 of 16

VB.NET LECTURE

The following code segment uses a For loop with an If statement to print out whether a number is odd or not. For pintCount = 0 To 100 If pintCount Mod 2 = 0 Then Debug.WriteLine("The number is even.") Else Debug.Writeline("The number is odd.") End If Next Example 2b Display expected population of a country for the next 7 years Suppose the population of a country is 1125000 this year (2005) and is growing at the rate of 1.9% yearly. Write a VB.NET program to perform this task and display the results in a listbox.

Public Class FrmGrowth Inherits System.Windows.Forms.Form Windows Form Designer generated code Private Sub cmdgrowth_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdgrowth.Click Dim pop As Double = 1125000 Const yr As Integer = 2005 Dim year As Integer Dim fmtstr As String = "{0,4}{1,16:N0}" lstGrowth.Items.Clear() lstGrowth.Items.Add(String.Format(fmtstr, "Year", "Population")) For year = yr To yr + 7 lstGrowth.Items.Add(String.Format(fmtstr, year, pop)) pop += 0.019 * pop Next End Sub Private Sub cmdExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdExit.Click Me.Close() End Sub End Class

Lecturer: Mr Ajit Gopee

Page 15 of 16

VB.NET LECTURE
Home Work Exercise 1 Amount Simple Interest and Amount Compound Interest
When $2500 is deposited at 7% simple interest the amount will grow by $175 yearly and the same money is deposited at 7% compound interest the amount at the end of each year is 1.07 times the amount at the beginning of that year. Write a VB.NET program to display the amount simple interest and the amount compound interest in a list box for 10 years.

Home Work Exercise 2 Radioactive Decay


Cobalt 60, a radioactive element used in cancer therapy, decays over a period of time. Each year 12% of the amount present at the beginning of the year will be decayed. If a container of Cobalt 60 initially contains 15 gms, write a VB.NET program to determine the amount of this element remaining after 8 years.

Lecturer: Mr Ajit Gopee

Page 16 of 16

Você também pode gostar