control structures part 1 if then control. index of projects in this ppt absolute value simple...
Post on 20-Dec-2015
213 views
TRANSCRIPT
Control structures
Part 1 if then control
Index of projects in this ppt
• Absolute value• Simple payroll• Letter grade assignment• Dental billing• GPA calculator• Boolean operations –nearly completed• Security panel• GPA calculator revisited for + and - grades• Quadratic equation –two versions
If statement
• An If statement is used to make a (run time) decision on how processing should occur.
• Code is provided for each case.• Examples:
– Should employee get overtime pay?– Is a numeric value greater than zero?– What letter grade should be assigned for a
student?
The if stmt is the simplest control structure
Simple if syntax:
If condition thenStmts go hereEnd if
condition
• The condition is a boolean expression. • It could be a boolean variable or an
expression involving booleans.• It could be a comparison between
comparable variables and values• Typically, we use operators =, >, <,
<>,<=,>= to compare numerical expressions for equality, greater than, less than, not equal, etc.
Example 1
• If you have declared
Dim val as Integer
• Then the following are legal boolean expressions (but not necessarily legal VB statements)Val=0 ‘ is val zero?
Val<0 ‘is val less than zero?
Val<>0 ‘is val different from zero
Example 2
• If you have declared
Dim hours as Single ‘ or Double
• Then the following are legal boolean expressions (but not necessarily legal VB statements)hours<40 ‘work less than 40 hours?
Hours>40 ‘work overtime?
Hours<>0 ‘work any hours this week?
Example 2A
• Assuming variables for othours, hoursworked, basepay and pay of type double (or single) you could use an if to calculate overtime pay:
If hoursworked>40 then
Pay= othours*1.5*rate+basepay
endif
Example 3
• If you have declared
Dim ok as Boolean
• Then the following are legal boolean expressions (and legal VB statements )Ok=false ‘is it false? Set it false.
Ok=a>b ‘set ok to the result of another compare operation
Putting things together
• An application that displays the absolute value of a (real) number
How does it work?
• I defined txtInput_Click event.
• When the input box is clicked, I convert the input string into a decimal value.
• I check (use an if!) to see if it is less than zero (and multiply it by -1 if it is).
• Otherwise the value is displayed unchanged.
The event handling subroutine Private Sub txtInput_click(ByVal sender As
System.Object, ByVal e As System.EventArgs) Handles txtInput.Click
Dim input As String Dim value As Doubletry ‘check to make sure input is numeric value = Double.Parse(txtInput.Text) If value < 0 Then value = -value ‘flip to positive if it was neg End If lblAnswer.Text = "absolute value is " &
value.ToString()Catch…End try End Sub
What I didn’t do
• I didn’t bother checking for legal input.
• I’ll leave as an exercise to add a try… catch…
Simple payroll
Simple payroll
In button click event handler
Dim rateString, HoursString As String Dim rate, hours, pay As Double rateString = txtRate.Text HoursString = txtHours.Text‘should put try catch hererate = Decimal.Parse(rateString) hours = Decimal.Parse(HoursString) pay = rate * hours ‘basic pay If hours > 40 Then ‘need to pay some overtime pay = pay + (hours - 40) * rate * 0.5 End If txtPay.Text = pay.ToString("C")End Sub
What about empty fields?
Lots more could be done
• Use try catch to find number format errors
• Display better error messages
To handle “either or” case
If condition then
True clause stmts
Else
False clause stmts
End if
To handle multiple cases
If boolean-expression then
Stmts
Elseif boolean-expression then
Stmts
Elseif….
Else: …’default… not handled above
End if
Reserved symbols
• If, else, then and end if are reserved symbols
• That means, for example, you can’t use them for var names.
Example 3: A letter grader
• User enters a student’s average (should be a real between 0 and 100)
• Form displays the letter grade to assign this student.
The letter grade example
The letter grade example
Input text changed code
Private Sub txtInput_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles txtInput.TextChanged
lblResult.Text = "hit calculate button"
End Sub
Buttonclick code Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnCalc.Click Dim input, answer As String Dim ave As Double input = txtInput.Text answer = "Grade is " Try ‘try…catch needed for number format exception ave = Decimal.Parse(input) If ave < 50 Then answer &= "E“ ‘must be E ElseIf ave < 60 Then answer &= "D“ ‘E already assigned, so it must be D ElseIf ave < 75 Then answer &= "C“ ‘etc ElseIf ave < 85 Then answer &= "B" Else : answer &= "A“ ‘note colon for last case End If Catch ex As FormatException answer = "input error" End Try lblResult.Text = answer
End Sub
What could be added?
• Check to make sure the input is between 0 and 100.
Boolean operators
• And (andAlso), or (orElse), not, xor are operators for boolean values
• Not is a unary operator, the others are binary.
Boolean operators: And (andAlso)
• Generally, truth tables are used to display how each works.
A B A and B
False False False
False True False
True False False
True True TRUE
Or (OrElse)
A B A or B
False False False
False True True
True False True
True True TRUE
Xor
A B A xor B
False False False
False True true
True False true
True True false
A boolean operator form
A boolean operator form
• Uses a combobox for the user to select from. A combobox holds a collection, in this case strings, which the programmer enters into the properties for the control.
Items property is a collection: enter choices
A project to display the boolean operations
The boolean operations project• We’ll use a combobox, which gives the user a selection
of strings to choose from… we define the strings in an edit window
Names
• I named my labels lbl00, lbl01, lbl02, lbl10, lbl11, lbl12, etc.
• I named my combobox operators. Recommended naming of comboboxes starts with “cbo…”
The running form
xor
Combobox codePrivate Sub
operator_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles operator.SelectedIndexChanged
Dim choice As String
choice = operator.SelectedItem
lbl02.Text = False ‘ this one is always false
‘use if ..else stmt hereto check which cb ‘choice and assign labels values
End Sub
I do show all code for this example
• This is one of your choices for this week’s project but I did not provide any code for it here.
If examples: A Dental Billing Form
Our control logic
• On button click:– Clear previous total
• If no name entered or no boxes checked display message
– Else• Set billtotal to zero
• if cleaning is checked add cleaning cost to total
• if filling is checked add filling cost to total
• if x-ray is checked add xray cost to total
• Display total (as currency)
The working Dental Billing form
Failed to enter name
Failed to select service
Button click code Private Sub btnCalc_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalc.Click Dim total As single Dim clean, fill, xray As Boolean Dim name As String total = 0 name = txtName.Text clean = cbClean.Checked fill = cbfill.checked xray = cbXRay.Checked If name = "" Then 'no name given txtTotal.Text = "You must enter name" Else ‘make sure a service is selected If Not (clean Or fill Or xray) Then 'error no service txtTotal.Text = "You must select services" Else 'seems to be a name and services If clean Then total += Decimal.Parse(lblClean.Text.Substring(1)) ‘total =total +35.50 End If If xray Then total += Decimal.Parse(lblXRay.Text.Substring(1)) End If If fill Then total += Decimal.Parse(lblFill.Text.Substring(1)) End If txtTotal.Text = total.ToString("C")
End If
End If End Sub
Other ways to do it
• You could open a messagebox to display errors• When a checkbox click state is changed you
could display a message for the user to recalculate the bill total
• I got the numeric value of services out of the labels using substring. This could be done differently… for example, define numeric fields in the class for service costs and use these numbers both for label display and to add up the total.
A GPA calculator
• Allow grades to be entered.
• Compute GPA for current list of grades
The GPA calculator: checks data
GPA calculator keeps a list
GPA calculator uses listbox
• You’ll need to look at next slideshow or in your book to see how to add and configure and use a listbox
GPA calculator computes current GPA
How does it work?
• You need to keep track of both current count of grades entered and current tally of grade values
• Those will need to be field values and you need to initialize them before processing begins.
How does it work?
• In add grade button, check the grade for legal value, and then add it to the list if it’s ok
• In compute gpa button, check to make sure gradecount>0. If it is go ahead and display the gpa (the quotient of sum of grades divided by count of grades).
• I used a function to return grade’s point value
Add button event sub• Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnAdd.Click• Dim grade As String• grade = txtLetter.Text• If grade <> "A" And grade <> "B" And grade <> "C" And grade <> "D" And grade <> "E"
Then• MessageBox.Show("you must enter A,B,C,D,or E", "input error", MessageBoxButtons.OK
_• , MessageBoxIcon.Error)• Else• lstGrades.Items.Add(grade)• gradecount += 1• gradesum += getValue(grade)• ' txtGPA.Text = gradecount.ToString() & " " & gradesum.ToString()• End If• txtLetter.Clear()
• End Sub•
A function to return grade value from a String
Private Function getValue(ByVal grade As String) As Double If grade = "A" Then getValue = 4.0 ElseIf grade = "B" Then getValue = 3.0 ElseIf grade = "C" Then getValue = 2.0 ElseIf grade = "D" Then getValue = 1.0 Else :
End IfEnd Function
getGPA button eventPrivate Sub btnGPA_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnGPA.Click Dim gpa As Double Dim answer As String answer = "error" If gradecount <> 0 Then gpa = gradesum / gradecount answer = gpa.ToString("N") End If txtGPA.Text = answer
End Sub
Disabling/enabling a button
• The field enabled on a button can be set to true or false in properties or in your code to turn on or turn off a button.
• We could change the GPA calculator so until grades have been entered the getGPA button is not enabled.
• We could also disable the getGPA button after GPA is calculated, until a new grade is entered.
GPA button.enabled set to false
After a legal grade is entered…
The code to do it
• In formload or in class initializations add the code:
btnGPA.Enabled =false
• In the if statement in buttonAddGrade event handler, when a legal grade is accepted, put the code:
btnGPA.Enabled =true
Focus
• You can change focus by having the control who should get focus next execute a
Control.focus()• In the GPA project, when the form is
loaded, and after any button is pressed, we could send the focus back to the letter grade textbox with the code
• txtLetter.focus()
After getGPA button is pressed
Security panel project
features
• Uses select case…control structure
• Textbox readonly set to true and password character set to ‘*’ in properties.
Select case expression
• Select case is equivalent to a multipart if else structure• It has the form
Select case expCase val1StmtsCase val2Stmts…Case else ‘optionalEnd select
• Here val1, val2 etc., are possible values of the expression exp, and the else case (optional) will handle all other cases.
functionality
• Each digit button just adds a digit (String, as in “1”, or “2”, etc) to a string holding the current code.
• The clear button sets the code to “” and the # key checks the valeu of the code.
• The string code is cleared after checking, and when the form is loaded as well as in the clear button event.
• The pound button displays the access provided to the given password
Btnpound event-handlerPrivate Sub btnpound_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnpound.Click Dim intcode As Integer Dim message As String intcode = Integer.Parse(code) code = "" txtcode.Text = code Select Case intcode Case 1234 message = "OK" Case 3456 message = "OK" Case 5555 To 6666 message = "limited" Case Else message = "restricted" End Select lststatus.Items.Add(message)
End Sub
Substring function
• The substring function of strings takes one or two integer arguments.
• If you give one integer argument, it returns the substring of the original from that char position, to the end.
• If you give two arguments, it returns the substring that starts at the first position and is the length of the second.
• String subscripts start at 0, not 1.
Example VB
Substring button code
Private Sub btnGo_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnGo.Click
Dim text As String Text = txtinput.Text lbl1.Text = "substring(0):" & text.Substring(0) lbl2.Text = "substring(2,4):" &
text.Substring(2, 4) lbl3.Text = "substring(5):" & text.Substring(5) End Sub
Revisitng GPA calculator
For GPA calculator
• You may also want to convert strings (that is, “ “ entities) into chars
• Two ways to do it:
• Convert.tochar(string)
• String.chars(position)
An input tester for GPA calculator
Illegal input
Code in button Dim text As String Dim first, second As Char Text = txtinput.Text lbl1.Text = "substring(0,1):" & text.Substring(0, 1) lbl2.Text = "substring(1,1):" & text.Substring(1, 1) first = text.Chars(0) second = Convert.ToChar(text.Substring(1, 1)) If text.Length > 2 Then lbllength.Text = "too long" Else lbllength.Text = "length ok" End If If first = "A" Or first = "B" Or first = "C" Or first = "D" Or first = "E" Then lblfirst.Text = first & " is legal" Else lblfirst.Text = first & " not legal" End If If second = "+" Or second = "-" Then lblsecond.Text = second & "is ok" Else lblsecond.Text = second & "not legal" End If
Quadratic equation form
Numeric operations exercises
• declare x1, x2, a, b, and c to be type double
• get values for a, b, and c from (hypothetical) textboxes txta, txtb, and txtc.
• Compute x1 and x2, the roots of the quadratic equation: ax2+bx+c
• Recall: root= (-b+/-sqrt(b2-4ac))/2a• Complete a VB form to do this as an
exercise.
Quadratic equation 1
Quadratic equation 2
An Aside on Text alignment for textboxes and labels
Select one to align text R/center/L and up/center/down