我有一个程序,每次按下按钮时都需要存储来自字段的用户输入,并保持运行总计。
理想情况下,button_click应该抓住用户输入的数字,并将其添加到Integer RunningTotal以创建int RunningTotal的更新值。
每次我输入一个新的整数并按下按钮时,都应该这样做。
例如,我输入5,单击按钮,RunningTotal = 5。 我输入5,单击按钮,RunningTotal = 10。
问题是它像每次迭代(按钮单击)都是FRESH一样运行此代码,并且不存储变量中的任何数据。
根据请求使用代码进行编辑:
Private Sub PickUp_Click(sender As Object, e As EventArgs) Handles PickUp.Click
Dim userInput As Integer = PickUpInputTextBox.Text
Label2.Visible = False
SetNumInputTB.Visible = False
SetNum.Visible = False
SetNum.Enabled = False
Dim ComputerNum As Integer
Dim InputNumber As Integer
Dim ComputerSticks As Integer
Dim PlayerSticks As Integer
Dim RunningTotal As Integer
InputNumber = SetNumInputTB.Text
ComputerNum = Int((inputNumber / 2) * Rnd() + 1)
MsgBox("The computer picked " & ComputerNum & " sticks")
ComputerSticks = ComputerNum
PlayerSticks = PickUpInputTextBox.Text
RunningTotal = PlayerSticks + ComputerSticks
MsgBox("Player Sticks:" & PlayerSticks & "Computer Sticks" & ComputerSticks & "Running Total: " & RunningTotal)
If RunningTotal >= InputNumber Then
determineWinner(1)
End If
End Sub
答案 0 :(得分:2)
问题是您的RunningTotal
是在button_click
函数中定义的。因此,无论何时调用该函数(单击按钮时),变量都会重新初始化。在您的主类的button_click
子类之外定义它,并按如下方式使用它:
Dim RunningTotal as Integer = 0
'.... other class code
Sub button_click()
'let us assume use input is stored in a variable called input
RunningTotal += input
End Sub
答案 1 :(得分:1)
您可以尝试声明静态变量,即。静态按钮单击为整数。
答案 2 :(得分:0)
当用户在TextBoxes中键入不是有效整数的内容时,您的程序将崩溃。使用Integer.TryParse()确定是否输入了有效的整数。
例如,更改:
Auth()
类似:
Dim userInput As Integer = PickUpInputTextBox.Text