从txt文件中读取并使用Public Function

时间:2013-11-18 17:08:43

标签: vb.net function visual-studio-2012 option-strict

嘿大家我在这里有一些代码从文件中引入一行文本并显示到标签中。我想从标签中添加八个值并除以8得到平均值,并将该平均分数转换为将在新标签中显示的字母等级。 我需要帮助的代码是在btnCal程序中。

这是我的代码:

   Imports System.IO

   Public Class Form1
    Dim grade As String

    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click
    Me.Close()

     End Sub

     Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles      OpenToolStripMenuItem.Click

    OFDG1.Filter = "Text Files|*.txt|All Files|*.*"
    Dim myResult As DialogResult
    myResult = OFDG1.ShowDialog
    If myResult = Windows.Forms.DialogResult.OK Then
        Dim strReader As StreamReader = File.OpenText(OFDG1.FileName)
        Dim aline As String
        Do Until strReader.EndOfStream
            aline = strReader.ReadLine
            Dim myStuff() = aline.Split(","c)
            lblStudent.Text = myStuff(0)
            lblClassField.Text = myStuff(1)
            lblSemesterInput.Text = myStuff(2)
            picStudent.Image = Image.FromFile(myStuff(3))
            lblInput1.Text = myStuff(4)
            lblInput2.Text = myStuff(5)
            lblInput3.Text = myStuff(6)
            lblInput4.Text = myStuff(7)
            lblInput5.Text = myStuff(8)
            lblInput6.Text = myStuff(9)
            lblMidtermInput.Text = myStuff(10)
            lblFinalInput.Text = myStuff(11)

        Loop
        strReader.Close()
    Else
        MessageBox.Show("You clicked other than OK")

    End If
End Sub

Private Sub btnCal_Click(sender As Object, e As EventArgs) Handles btnCal.Click

    grade = CStr(CInt(lblInput1.Text + lblInput2.Text + lblInput3.Text _
    + lblInput4.Text + lblInput5.Text + _
    lblInput6.Text + lblMidtermInput.Text + lblFinalInput.Text / 8)

    lblFinalLetterGrade.Text = Calculation(CInt(grade))

End Sub
Public Function Calculation(ByVal grade As Integer) As String
    Select Case grade
        Case Is > 89
            Return "A"
        Case Is > 79
            Return "B"
        Case Is > 69
            Return "C"
        Case Is > 59
            Return "D"
        Case Else
            Return "F"
    End Select
End Function
End Class 

1 个答案:

答案 0 :(得分:1)

你正在混合连接(你可以使用+两者,只要你没有指出正确的类型(整数),VB.NET认为你的意思是字符串,只是连接它们。为了避免这种错误,最好使用&进行连接并让+仅用于添加)而不是放置正确的括号(在添加之前考虑除法)。

grade = CStr((CInt(lblInput1.Text) + CInt(lblInput2.Text) + CInt(lblInput3.Text) _
    + Cint(lblInput4.Text) + CInt(lblInput5.Text) + _
    CInt(lblInput6.Text) + CInt(lblMidtermInput.Text) + CInt(lblFinalInput.Text)) / 8)

一般来说,您似乎应该在正确构建代码方面多做一些工作。您也使用了旧VB中的一些方法(例如CStrCInt);有时候没有问题,其他时候可能会导致令人困惑的代码(例如,.NET索引始终从0开始,而某些旧函数从1开始)。另一方面,如果您使用VB.NET编程,为什么要使用VB6代码呢?