Public Class convertGrades
'Here is where I declare my variables
Dim numbergrade As Integer
Dim lettergrade As Char
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'This is an If/Else statement that allows the user to
'convert their number grade into a letter grade
txtNumberGrade.Text = numbergrade
lblLetterGrade.Text = lettergrade
If (numbergrade >= 90 Or numbergrade <= 100) Then
lettergrade = "A"
ElseIf (numbergrade >= 80 Or numbergrade <= 79) Then
lettergrade = "B"
ElseIf (numbergrade >= 70 Or numbergrade <= 89) Then
lettergrade = "C"
ElseIf (numbergrade >= 60 Or numbergrade <= 69) Then
lettergrade = "D"
ElseIf (numbergrade >= 50 Or numbergrade <= 59) Then
lettergrade = "F"
End If
txtNumberGrade.Focus()
End Sub
This is the exact code I have, I am using Visual Basic 2012 and am having trouble converting these numbers into letter grades. VB says I have no errors but when I run it, the program does not convert the numbers into letters. Any suggestions?
You swapped the high number for the B and C grades. Also, you probably want AndAlso
for these checks, rather than Or
. While I'm here, as a matter of good program design, you should abstract this out to a separate method. The final result:
Public Function LetterGradeFromScore(ByVal score As Integer) As Char
If numbergrade >= 90 Then
Return "A"c
ElseIf numbergrade >= 80 AndAlso numbergrade <= 89 Then
Return "B"c
ElseIf numbergrade >= 70 AndAlso numbergrade <= 79 Then
Return "C"c
ElseIf numbergrade >= 60 AndAlso numbergrade <= 69 Then
Return "D"c
Else
Return "F"c
End If
End Function
'The only code that lives in this method is code that directly updates or responds to the UI
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
txtNumberGrade.Text = numbergrade
lblLetterGrade.Text = LetterGradeFromScore(numbergrade)
txtNumberGrade.Focus()
End Sub
Another thing: VB.Net has a really nice Select Case
syntax you can use for this:
Public Function LetterGradeFromScore(ByVal score As Integer) As Char
Select Case score
Case >= 90
Return "A"c
Case 80 to 89
Return "B"c
Case 70 to 79
Return "C"c
Case 60 to 69
Return "D"c
Case Else
Return "F"c
End Select
End Function
Finally, you could avoid a problem like swapping the number above, and as well as improve the code, by converting this to a kind of table lookup:
Public Function LetterGradeFromScore(ByVal score As Integer) As Char
'This could be a Shared Member somewhere, or even stored in a DB and populated on load
Dim gradeMap As New SortedList(Of Integer, Char)(5)
gradeMap.Add(90, "A"c)
gradeMap.Add(80, "B"c)
gradeMap.Add(70, "C"c)
gradeMap.Add(60, "D"c)
gradeMap.Add( 0, "F"c)
Return gradeMap.Last(Function(m) m.Key < score).Value
End Function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.