2013-08-10 4 views
2

데이터 유형에 대한 입력 상자를 구문 분석 할 수 있는지 궁금하고 데이터 유형과 일치하지 않으면 올바른 유형이 완료 될 때까지 반복됩니다. 나는 범위로 이것을하는 방법을 이해하지만 그것이 가능하다면 오히려하지 않을 것이다.이 GoTo를 어떻게 제거합니까?

내가 가진 코드는 다음과 같습니다

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 

나는 고토는 "오른쪽"또는 선호하는 해결책이 아니다는 것을 알고 있지만 나는 임시 장소 홀더로 더 것을 사용했다. 이것이 현재 나의 프로그래밍 능력을 초월한 어떤 도움이라도 인정 될 것입니다. 이 데이터 유형 에 대한 입력 상자를 구문 분석 할 수있는 경우

+0

'Return'을 사용 하시겠습니까? –

+3

예외 핸들러 추가 - http://msdn.microsoft.com/en-us/library/fk6t46tz.aspx – OldProgrammer

+0

break 문을 사용할 수 있습니다 ... – Pankaj

답변

1

나는 궁금와 일치하지 않을 경우 데이터가 올바른 유형이 완료 될 때까지 루프 것이다 입력합니다.

Integer.TryParse이 실패하면 다시 시도하는 함수를 호출합니다.

Private Function AskInteger(prompt As String) As Integer 
    Dim result As Integer 
    If Not Integer.TryParse(InputBox(prompt), result) Then 
     MessageBox.Show("An error has occurred...") 
     Return AskInteger(prompt) 
    End If 
    Return result 
End Function 

이 구문 분석에 성공할 때까지 계속 마지막으로 정수를 반환하므로 안전하게 오류 검사없이 호출 할 수있는 것입니다 : 모든

pointsEarned = AskInteger("Please enter the amount...") 
+0

왜이 문제에 대한 재귀 적 솔루션을 원하십니까? do ... 루프를 사용하십시오. –

+0

@MatteoItalia 루프가 명시 적으로 TryParse의 결과를 두 번 확인해야 할 필요가 있기 때문에 좀 더 간결하다고 생각했습니다. – nmclean

0

첫째, 당신이와 가지고 각각의 모든 On Error GoTo 교체 Try-Catch 문을 사용하거나 최소한 GoTo 대신 함수를 사용하십시오! GoTo를 사용하는 것은 매우 나쁜 습관입니다. 특히 나중에 뭔가를 업데이 트하거나 누군가 다른 사람이 코드를 읽으 려하면 매우 어려울 것입니다 큰 고통이 될 것입니다. 참조 : http://forums.devshed.com/showpost.php?p=2605339&postcount=3http://www.drdobbs.com/jvm/programming-with-reason-why-is-goto-bad/228200966. 여기

이 기능을 사용 Dim theInt As Integer = GetInput("123", 5)를 실행하는 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 

그리고 물론 조금 향상된 버전입니다.

마크 홀, 함수에 추가 한 코드 전체를 더 잘 만들 수 있다고 생각하지 않습니까? 내가 그랬던 것처럼. 그러면 코드 줄을 줄일 수 있습니다.

+0

예제 호출은 NumOfRetries 매개 변수의 값을 제공하지 않으므로 해당 값은 선택 사항이 아니므로 컴파일되지 않습니다. –

+0

오타를 유감스럽게 생각합니다. 방금 고쳤어. :) –

2

구문 분석 대신 모든 변환에 Integer.TryParse를 사용하는 것이 좋겠지 만 변환 및 오류없이 변환이 실패했는지 여부를 테스트 할 수 있습니다. 이 같은 것이 작동해야합니다.

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 
관련 문제