首页 > 解决方案 > 将文字转换为常量

问题描述

我是一名学习 Visual Basic 的新程序员。
现在,我正在做一个关于垒球记分牌的项目。我只使用过文字,所以我没有意识到我的老师想要常量。

不过我很困惑,因为我不确定 2 之间的区别或者我如何将我的文字变成常量。

如果您能提供帮助,我将不胜感激。谢谢你。

Public Class frmSoftballScoreboard
    'Declaring array
    Dim scores(7) As Double
    'declaring variables
    Dim runs As String
    Dim runningScore As Integer = 0
    Dim i As Integer = 0
    Dim out As Double

    'page load event
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        lstScores.Items.Add("Runs Running Score")
    End Sub
    'Enter score button
    Private Sub btnScore_Click(sender As Object, e As EventArgs) Handles btnScore.Click

        If i < 7 Then
            'display inputbox to the user
            runs = InputBox("Enter score for " & (i + 1) & " innings", "Score")
            'if runs is entered
            If runs <> "" Then
                'parse the value of runs
                If (Double.TryParse(runs, out)) Then
                    'parse the runs and add it to the array scores()
                    scores(i) = Double.Parse(runs)
                    runningScore += scores(i)
                    'add the rainfall value to the listbox along with month name
                    lstScores.Items.Add(scores(i) & " :" & runningScore)
                    'increment the value of i
                    i = i + 1
                Else
                    'display error message
                    MessageBox.Show("Enter valid runs value")
                    lblTotal.Text = ""
                End If
            Else
                'if runs is empty then display error message
                MessageBox.Show("Enter runs for " & i & "innings")
            End If
        Else
            MessageBox.Show("Only sever innings are allowed")
        End If
        'calculate total runs And display on the lable
        lblTotal.Text = String.Format("final score is {0}", scores.Sum())
    End Sub
    'Clear Menu click
    Private Sub ClearToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuClear.Click
        lstScores.Items.Clear()
        lblTotal.Text = ""
        'reset i to 0
        i = 0
    End Sub
    'Exit Menu click
    Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles mnuExit.Click
        'close application
        Application.Exit()
    End Sub
End Class

标签: vb.net

解决方案


这是一个示例,您可以如何做到这一点。

带有文字的旧代码:

MessageBox.Show("All well done!")

改为使用常量的代码:

Const SUCCESS_MESSAGE As String = "All well done!"

MessageBox.Show(SUCCESS_MESSAGE)

常量中有占位符的样本:

Const REPLACE_MESSAGE_SAMPLE As String = "This is Number #!"

Dim i As Integer
i = 123

MessageBox.Show(REPLACE_MESSAGE_SAMPLE.Replace("#", i))

您可以使用任何您喜欢的字符串来代替#. 这只是一个样本。

顺便说一句:您的代码看起来像VB.NET而不是VBA. 我编辑了它。


推荐阅读