Date post: | 20-Dec-2015 |
Category: |
Documents |
View: | 219 times |
Download: | 0 times |
VB.Net Introduction - 2
Counter
• Example: Keep track the number of times a user clicks a button
• Need to declare a variable:Dim Counter As Integer
• Need to increase the counter by 1Counter = Counter + 1
Question: Where to declare this variable?
Variable Scope• Block-level scope: declared within a block of code
terminated by an end, loop or next statement.– If city = “Rome” then
• Dim message as string = “the city is in Italy”
• MessageBox.Show(message)
– End if
• Procedural-level scope: declared in a procedure• Class-level, module-level scope: declared in a
class or module but outside any procedure with either Dim or Private keyword.
• Project-level scope: a module variable declared with the Public keyword.
Sum• Example: Create a form with one textbox to enter
number, and a button to add the number to a variable Sum to compute the total of all numbers, and button to show the Sum:
Dim Sum As Double
Sum = Sum + textbox1.text
• Interface issue: Should we clear the textbox after adding the number to Sum?
TextBox1.Clear()
• Data conversion issue: What if data entered is not numeric?
Error Handling with the Try Statement
Try Sum = Sum + TextBox1.Text TextBox1.Clear()Catch MessageBox.Show("Pls enter a number") End Try
Display Error Message with the Try Statement
Try Sum = Sum + TextBox1.Text TextBox1.Clear()Catch ex As Exception MessageBox.Show(ex.Message) End Try
Simple Calculator
• Create a form with two textboxes to enter numbers and buttons to do +, -, *, / and Mod.
Format
• C, F, N, P
• toString(“C”)
Multiple FormsTo open a form:
formName.Show, formName.ShowDialog
Two forms: Form1, Form2To Open Form2 from Form1:
Form2.ShowDialog
.
• Modeless form: Other forms can receive input focus while this form remains active.– FormName.Show()
• Modal form: No other form can receive focus while this form remains active.– FormName.ShowDialog()
Configure VB Project
• Project property page– Application– Compile– References
• Tools/Options– Environment
– Projects and Solutions
» VB defaults
VB Defaults
• Option Explicit: – On --- must declare variables before use
• Option Strict:– Off --- VB will convert the data
• Option Compare:– Binary --- case sensitive– Text --- case insensitive
• Option Infer– On --- When you set Option Infer to On, you can declare variables
without explicitly stating a data type. The compiler infers the data type of a variable from the type of its initialization expression.
Decision Structure
Decision: Action based on conditionExamples
• Simple condition:– If total sales exceeds $300 then applies 5%
discount; otherwise, no discount.
• More than one condition:• Taxable Income < =3000 no tax• 3000 < taxable income <= 10000 5% tax• Taxable income > 10000 15% tax
• Complex condition:– If an applicant’s GPA > 3.0 and SAT > 1200:
admitted
Relational Operators Test Conditions
• Usually a condition is formed using a relational operator
• A relational operator determines if a specific relationship exists between two values> Greater than< Less than= Equal to<> Not equal to>= Greater than or equal to<= Less than or equal to
The If … Then Statement• If condition Then
Statements
• End If
• If condition ThenStatements
ElseStatements
• End If
• Note: The If and the Then must be on the same line
If…Then Examples‘Bonus awarded if sales greater than 50000 If sales > 50000 Then
getsBonus = TrueEnd If
‘Bonus, 12% commission rate, and a day off‘awarded if sales greater than 50000If sales > 50000 Then
getsBonus = TruecommissionRate = 0.12daysOff = daysOff + 1
End If
Example: If total sales is larger than 1000, then give 5% discount
totalSales=textbox1.textdisCount=0If totalSales > 1000 Then discount=0.05End if
totalSales=textbox1.textIf totalSales > 1000 Then discount=0.05Else discount=0End if
Example: If with a block of statements
If totalSales > 1000 ThendiscountRate=0.05
NetPay=totalSales*(1-discountRate)MessageBox.Show(“Thank you very much”)
ElsediscountRate=0
NetPay=totalSalesMessageBox.Show(“Thank you”)
End if
More than one condition
Rules for bonus:
JobCode = 1 300JobCode = 2 500JobCode = 3 700JobCode = 4 1000
IF Statement with ElseIf
• IF condition THEN
statements
[ELSEIF condition-n THEN
[elseifstatements]
[ELSE
[elsestatements]]]
End If
Code Example
If JobCode = 1 Then Bonus = 300ElseIf JobCode = 2 Then Bonus = 500ElseIf JobCode = 3 Then Bonus = 700Else : Bonus = 1000End If
If JobCode = 1 Then Bonus = 300ElseIf JobCode = 2 Then Bonus = 500ElseIf JobCode = 3 Then Bonus = 700ElseIf JobCode = 4 Then Bonus = 1000End If
Example of ElseIf Usage
If sngAverage < 60 ThenlblGrade.Text = "F"
ElseIf sngAverage < 70 ThenlblGrade.Text = "D"
ElseIf sngAverage < 80 ThenlblGrade.Text = "C"
ElseIf sngAverage < 90 ThenlblGrade.Text = "B"
ElseIf sngAverage <= 100 ThenlblGrade.Text = "A"
End If
• Does the order of these conditions matter?
• What happens if we reverse the order?
Slide 4- 24
The Same Rules Without ElseIfIf sngAverage < 60 Then
lblGrade.Text = "F"End IfIf sngAverage < 70 Then
lblGrade.Text = "D"End IfIf sngAverage < 80 Then
lblGrade.Text = "C"End IfIf sngAverage < 90 Then
lblGrade.Text = "B"End IfIf sngAverage <= 100 Then
lblGrade.Text = "A"End If
• Does this code function correctly? What is assigned to lblGrade for a 65 average? 75?
Bonus Example
If JobCode = 1 Then Bonus = 300End IfIf JobCode = 2 Then Bonus = 500End IfIf JobCode = 3 Then Bonus = 700End IfIf JobCode = 4 Then Bonus = 1000End If
If JobCode = 1 Then Bonus = 300ElseIf JobCode = 2 Then Bonus = 500ElseIf JobCode = 3 Then Bonus = 700ElseIf JobCode = 4 Then Bonus = 1000End If
Use of a Trailing Else
If sngAverage < 60 ThenlblGrade.Text = "F"
ElseIf sngAverage < 70 ThenlblGrade.Text = "D"
ElseIf sngAverage < 80 ThenlblGrade.Text = "C"
ElseIf sngAverage < 90 ThenlblGrade.Text = "B"
ElseIf sngAverage <= 100 ThenlblGrade.Text = "A"
ElselblGrade.Text = "Invalid"
End If
• If average is greater than 100, lblGrade is assigned the text “Invalid”
Nested IF
• State University calculates students tuition based on the following rules:– State residents:
• Total units taken <=12, tuition = 1200
• Total units taken > 12, tuition = 1200 + 200 per additional unit.
– Non residents:• Total units taken <= 9, tuition = 3000
• Total units taken > 9, tuition = 3000 + 500 per additional unit.
Decision Tree
Resident or Not
Units <= 12 or Not
Units <= 9 or Not
Nested If Example
If sngSalary > 30000 ThenIf intYearsOnJob > 2 Then
lblMessage.Text = “Applicant qualifies."Else
lblMessage.Text = “Applicant does not qualify."End If
ElseIf intYearsOnJob > 5 Then
lblMessage.Text = “Applicant qualifies."Else
lblMessage.Text = “Applicant does not qualify."End If
End If Note how the convention of indentationsemphasizes the structure of nested Ifs.
• A bank customer qualifies for a special loan if:– Earns over 30000 & on the job more than 2 years– Or been on the job more than 5 years
Select Case Structure
• SELECT CASE testexpression
[CASE expressionlist-n
[Statements]
[CASE ELSE
[elsestatements]
END SELECT
Select Case Example• SELECT CASE temperature
CASE <40Text1.text=“cold”
CASE < 60Text1.text=“cool”
CASE 60 to 80Text1.text=“warm”
CASE ELSEText1.text=“Hot”
End Select
The Expression list can contain multiple expressions, separated by commas.
Select Case number
Case 1, 3, 5, 7, 9
textBox1.text=“Odd number”
Case 2, 4, 6, 8, 10
textBox1.text=“Even number”
Case Else
End Select
Complex Condition
• Examples:– A theater charges admission fee based on
customer’s age:• 12 <= Age <= 65: Fee = $5
• Otherwise: Fee = $3
– X University admission rules:• If GPA > 3.5 or SAT > 1500: Admitted
– Y University admission rules:• If GPA > 3.0 and SAT > 1200: Admitted
Logical Operators: AND, OR, NOT
• AND• Cond1 Cond2 Cond1 AND Cond2
T TT FF TF F
• OR• Cond1 Cond2 Cond1 OR Cond2
T TT FF TF F
• NOT• Cond NOT Cond
TF
Examples
• Write a complex condition for: 12 <= Age <= 65• Use a complex condition to describe age not
between 12 and 65.• X <= 15 is equivalent to: X<15 AND X =15? (T/F)• This complex condition is always false:
– X < 5 AND X > 10
• This complex condition is always true:– X >= 5 OR X <= 10
Example• Electric Company charges customers based on KiloWatt-Hour
used. The rules are:– First 100 KH, 20 cents per KH
– Each of the next 200 KH • (up to 300 KH), 15 cents per KH
– All KH over 300, 10 cents per KH
Complex Condition
• University admission rules: Applicants will be admitted if meet one of the following rules:– 1. Income >= 100,000– 2. GPA > 2.5 AND SAT > 900
• An applicant’s Income is 150,000, GPA is 2.9 and SAT is 800. Admitted?– Income >= 100,000 OR GPA > 2.5 AND SAT >900
• How to evaluate this complex condition?
• Scholarship: Business students with GPA at least 3.2 and major in Accounting or CIS qualified to apply:– 1. GPA >= 3.2– 2. Major in Accounting OR CIS
• Is a CIS student with GPA = 2.0 qualified?– GPA >= 3.2 AND Major = “Acct” OR Major = “CIS”
• Is this complex condition correct?
NOTSet 1: Young: Age < 30
Set 2: Rich: Income >= 100,000
Young Rich
Condition with Not
• University admission rules: Applicants will be admitted if meet all the rules:– 1. SAT > 900 OR Income >= 50,000– 2. Not GPA < 2.5
• Condition:– SAT > 900 OR Income >= 50,000 AND Not GPA < 2.5
– Correct?
Order of Evaluation
• 1. ()
• 2. Not
• 3. AND
• 4. OR