在设定值vb.net之间生成数字

时间:2014-05-03 12:53:01

标签: vb.net loops listbox

我正在创建一个程序来在值列表之间生成数字。 我遇到的问题是,如果第一个数字值小于第二个值,它将产生错误,例如1000和32将说它不起作用,或者532和64 我不明白为什么或如何解决它

Private Sub Generate_Click(sender As System.Object, 
      e As System.EventArgs) Handles Generate.Click

    'Displays to enter correct information if lower is <=
    If Upper.Text <= Lower.Text Or Lower.Text >= Upper.Text Then
        List.Items.Clear()
        List.Items.Add("Please enter correct info Upper # higher value than Lower #")
    Else

        'If Upper range is higher than lower range then display numbers until total value is displayed
        List.Items.Clear()
        Number.Text = ""
        Dim i As Integer = Lower.Text

        Do While i <= Upper.Text 'Loop generates the numbers between values specified
            List.Items.Add(i)
            i += 1
        Loop

        'Select a random value from the list generated
        Dim myRandom As New Random
        Dim b As Integer = List.Items.Count
        Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
        Number.Text = chosenItem.ToString

    End If

End Sub

2 个答案:

答案 0 :(得分:1)

基本上你必须比较你正在比较字符串的数值,以便它发生。

和&#39;或&#39; if语句中不需要条件,因此省略它。

请按以下方式替换您的代码。

if System.Convert.ToInt32(Upper.Text) <= System.Convert.ToInt32(Lower.Text) Then
    List.Items.Clear()
    List.Items.Add("Please enter correct info Upper # higher value than Lower #")
Else

    List.Items.Clear()
    Number.Text = ""
    Dim i As Integer = Lower.Text

    Do While i <= System.Convert.ToInt32(Upper.Text) 'Loop generates the numbers between values specified
        List.Items.Add(i)
        i += 1
    Loop

    'Select a random value from the list generated
    Dim myRandom As New Random
    Dim b As Integer = List.Items.Count
    Dim chosenItem As System.Object = List.Items.Item(myRandom.Next(b))
    Number.Text = chosenItem.ToString

End If

答案 1 :(得分:1)

使用If子句,您正在对数值进行字符串比较。您需要将它们转换为整数值。你正在进行两次相同的比较,这是不必要的。还有一种在两个整数之间生成随机数的简单方法。

我建议您使用页面顶部的“Option Strict On”声明进行编码。当您尝试进行隐式转换时,编译器会提醒您,其中代码中有多个转换。

Dim iMinimum As Integer = Integer.Parse(Lower.Text) 
Dim iMaximum As Integer = Integer.Parse(Upper.Text) 

If iMaximum <= iMinimum Then
    Number.Text = "Please enter correct info Upper # higher value than Lower #"
Else
    Dim randomObject As Random = New Random
    Number.Text = randomObject.Next(iMinimum, iMaximum).ToString
End If