vb.net - 将文字转换为常量
问题描述
我是一名学习 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
解决方案
这是一个示例,您可以如何做到这一点。
带有文字的旧代码:
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
. 我编辑了它。
推荐阅读
- recursion - 使用递归在 lambda 演算中创建有序对列表
- javascript - JavaScript 中两个字符串之间的常用字母
- r - 替换矩阵中的值:在每一行中,最大值与最小值
- arrays - 在 do/until 循环中打印 Powershell 数组属性在循环第一次迭代后显示空白行
- javascript - 转换之间的离子滞后
- python - Python 脚本在设置 tmp 文件夹时遇到问题
- java - 计算器宁静错误部署
- vb.net - 如何将字符串插入到符合条件的其他特定字符串中?
- oracle - 应用程序无法访问在 oracle 数据库中创建的表
- sharepoint-online - 无法将 Html 内容转换为 Pdf