【问题标题】:VB. Prime number checker. Invalid inputVB。质数检查器。输入无效
【发布时间】:2015-03-11 20:52:23
【问题描述】:

当我尝试添加 integer.tryparse 以处理无效输入并将消息读取为“无效输入”时,我的代码似乎无法正常工作。例如,如果数字是字母而不是数字。这是我目前所拥有的:

Public Class Form1

    Private Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles TextBox1.TextChanged
        Answer.Text = ""
    End Sub

    Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
        Dim iNum, iSum As Double
        Dim isPrime As Boolean = False
        iNum = Integer.Parse(TextBox1.Text)
        For i = 2 To Math.Sqrt(iNum) Step 1
            iSum = iNum Mod i
            If (iSum = 0) Then
                isPrime = True
                Exit For
            End If
        Next
        If isPrime Then
            Answer.Text = "Is Not Prime"
        Else
            Answer.Text = "Is Prime"
        End If
    End Sub


End Class

【问题讨论】:

  • 指向你正在使用TryParse的行。
  • 指向您提出问题的行。
  • Winforms、Webforms 还是 MVC?您是否尝试过使用验证器?显示您的 TryParse 代码并描述正在发生的事情。
  • 如果 winform:User Input Validation in Windows Forms。摘要:处理验证/验证事件。
  • 我不确定进入 tryparse 的最佳位置是哪里

标签: vb.net integer primes


【解决方案1】:

应该这样做:

Private Sub Button1_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles button1.Click
    Dim iNum, iSum As Double
    Dim isPrime As Boolean = False
    If Not Integer.TryParse(TextBox1.Text, iNum)
        Answer.Text = "invalid input"
    Else
        For i = 2 To Math.Sqrt(iNum) Step 1
            iSum = iNum Mod i
            If (iSum = 0) Then
                isPrime = True
                Exit For
            End If
        Next
        If isPrime Then
            Answer.Text = "Is Not Prime"
        Else
            Answer.Text = "Is Prime"
        End If
    End If
End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    相关资源
    最近更新 更多