vb.netvb6

Stepped table lookup in VB?


I use this code from the book that illustrates an example of a stepped table lookup:

Imports System
Imports Microsoft.VisuaLBasic

Public Module Module1

    Public Sub Main()
        Dim rangeLimit() as Double = {50.0, 65.0, 75.0, 90.0, 100.0}
        Dim grade() as String = {"F", "D", "C", "B", "A"}
        Dim maxGradeLevel = grade.length - 1

        Dim gradeLevel = 0
        Dim studentGrade = "A"
        Dim studentScore = 50

        While((studentGrade = "A") and (gradeLevel < maxGradeLevel))
            if(studentScore < rangeLimit(gradeLevel)) then
                studentGrade = grade(gradeLevel)
            End if
            gradeLevel = gradeLevel + 100
        End While
        Print(studentGrade)
    End Sub
End Module

Code is here

I wonder how it works and how to fix this error after compiling:

Run-time exception (line -1): Conversion from string "A" to type 'Integer' is not valid.

Solution

  • You probably want Console.WriteLine() instead of Print().

    Also:

    Imports System
    Imports System.Linq
    
    Public Module Module1
        Public Sub Main()
            Dim studentScore As Double = 50.0
            Console.WriteLine(GetGrade(studentScore))
        End Sub
        
        Public Function GetGrade(score As Double) As String
            Dim gradeTable = { 
                (50.0,  "F"), 
                (65.0,  "D"), 
                (75.0,  "C"), 
                (90.0,  "B"), 
                (100.0, "A") 
            }
            Return gradeTable.First(Function(g) g.Item1 >= Score).Item2
        End Function
    End Module
    

    See it work here:

    https://dotnetfiddle.net/CKTNCE

    Personally, though, I prefer to use the minimum grade instead of the maximum for the boundaries. I find it far more likely you'll have extra credit push a score above 100 than you'll have something send you a negative score, and using maximum grades causes problems in that situation:

    Imports System
    Imports System.Linq
    
    Public Module Module1
        Public Sub Main()
            Dim studentScore As Double = 50.0
            Console.WriteLine(GetGrade(studentScore))
        End Sub
        
        Public Function GetGrade(score As Double) As String
            Dim gradeTable = { 
                (90.0, "A"), 
                (75.0, "B"), 
                (65.0, "C"), 
                (50.0, "D"), 
                ( 0.0, "F") 
            }
            Return gradeTable.First(Function(g) g.Item1 >= Score).Item2
        End Function
    End Module
    

    You also need to be careful with your equality comparisons. >= and > mean different things, and only one is correct.