我是学习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
答案 0 :(得分:0)
下面是一个示例。
带有文字的旧代码:
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
。我编辑了。
答案 1 :(得分:0)
您应该使用带占位符的常量:
Const WARNING_MESSAGE$ = "The player {0} must be ready at {1}"
MsgBox(String.Format(WARNING_MESSAGE, "John Davis", #12/11/2018#))