0

大家好,我这里有一些代码,可以从文件中引入一行文本并显示到标签中。我想将标签中的八个值相加并除以 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 
4

1 回答 1

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 中的许多方法(例如CStr,,CInt);有时没有问题,有时可能会导致代码混乱(例如,.NET 索引总是从 0 开始,某些旧函数从 1 开始)。另一方面,如果您使用 VB.NET 进行编程,那您为什么要使用 VB6 代码呢?

于 2013-11-18T17:17:20.423 回答