2

データ型の入力ボックスを解析できるかどうかに興味があります。データ型と一致しない場合は、正しい型が完了するまでループします。範囲でこれを行う方法は理解していますが、可能であればそうではありません。

私が持っているコードは次のとおりです。

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 が「正しい」または推奨されるソリューションではないことはわかっていますが、それを一時的なプレースホルダーとして使用しました。これは現在の私のプログラミング能力を超えているため、どんな助けもいただければ幸いです。

4

3 に答える 3

0

まず、持っているすべてのOn Error GoToものを Try-Catch ステートメントに置き換えるか、少なくとも GoTo の代わりに関数を使用します。GoTo をまったく使用することは、非常に悪い習慣です。特に後で何かを更新するために戻ってきたり、他の誰かがコードを読み取ろうとしたりすると、非常に困難になります。http://forums.devshed.com/showpost.php?p=2605339&postcount=3およびhttp://www.drdobbs.com/jvm/programming-with-reason-why-is-goto-bad/228200966を参照してください。

これは、nmcleanの回答の少し強化されたバージョンです

Private Function GetInput(ByVal prompt As String, ByVal NumOfRetries As Integer) As Integer
    Try
        Return Integer.Parse(InputBox(prompt))
    Catch ex As Exception
        If NumOfRetries > 0 Then
            NumOfRetries -= 1
            Return GetInput(prompt, NumOfRetries)
        Else
            Return Nothing
        End If
    End Try
End Function

そしてもちろん、この関数を実行するにはDim theInt As Integer = GetInput("123", 5).

マーク・ホールさん、あなたが与えたコード全体を関数にするほうがいいと思いませんか? 私がしたように。これにより、数行のコードを節約できます。

于 2013-08-11T03:28:26.740 に答える