gpt4 book ai didi

vb.net - 如何删除此 GoTo?

转载 作者:行者123 更新时间:2023-12-04 04:46:06 25 4
gpt4 key购买 nike

我很好奇是否可以解析数据类型的输入框,如果它与数据类型不匹配,它将循环直到完成正确的类型。我了解如何使用范围来做到这一点,但如果可能的话,我宁愿不这样做。

我的代码是:

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click
Dim amountAssignments As Integer
Dim pointsEarned As Integer = 0
Dim pointsEarnedTotal As Integer = 0
Dim pointsPossible As Integer = 0
Dim pointsPossibleTotal As Integer = 0
Dim Assignment As Integer = 1

Integer.TryParse(txtAmount.Text, amountAssignments)

Do Until Assignment > amountAssignments
txtAmount.Text = String.Empty
pointsEarned = Integer.Parse(InputBox("Please enter the amount, as a whole number, of Points Earned for Assignment " & Assignment & ":"))
On Error GoTo Check
pointsEarnedTotal = pointsEarnedTotal + pointsEarned
pointsPossible = Integer.Parse(InputBox("Please enter the amount, as a whole number, of Points Possible for Assignment " & Assignment & ":"))
On Error GoTo Check
pointsPossibleTotal = pointsPossibleTotal + pointsPossible
Assignment = Assignment + 1
Loop

lblGrade.Text = (pointsEarnedTotal / pointsPossibleTotal)
Check:
MessageBox.Show("An error has occured, most likely due to an improper value in the points earned or possible box. Please try running the program again with proper values.", "Please run the program again", _
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)

End Sub

我知道 GoTo 不是“正确”或首选的解决方案,但我更多地将其用作临时占位符。任何帮助将不胜感激,因为这超出了我目前的编程能力。

最佳答案

我会考虑将 Integer.TryParse 用于所有转换而不是 Parse,这样您就可以测试转换是否失败而没有抛出和错误。像这样的东西应该工作

If Integer.TryParse(txtAmount.Text, amountAssignments) Then
Do Until Assignment > amountAssignments
txtAmount.Text = String.Empty
If Not Integer.TryParse(InputBox("Please enter the amount, as a whole number, of Points Earned for Assignment " & Assignment & ":"), pointsEarned) Then
showError()
Exit Sub
End If
pointsEarnedTotal = pointsEarnedTotal + pointsEarned
If Not Integer.TryParse(InputBox("Please enter the amount, as a whole number, of Points Possible for Assignment " & Assignment & ":"), pointsPossible) Then
showError()
Exit Sub
End If
pointsPossibleTotal = pointsPossibleTotal + pointsPossible
Assignment = Assignment + 1
Loop
lblGrade.Text = (pointsEarnedTotal / pointsPossibleTotal)
Else
showError()
End If

您的消息框已放入这样的子例程中。
Sub showError()
MessageBox.Show("An error has occured, most likely due to an improper value in the points earned or possible box. Please try running the program again with proper values.", "Please run the program again", _
MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
End Sub

关于vb.net - 如何删除此 GoTo?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18166725/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com