问题例外和随机数

时间:2011-03-27 20:21:32

标签: vb.net exception random

我在VB.NET中抽奖

当我模拟这个东西时,我得到了一个错误。要在文件中写入任何“方坯”产生的错误是:

  

无效的CastException未处理:“Double”链“[”的转换无效

另外,我不知道如何为每个Billet对象编制一系列1到49之间的随机数

这是我的代码

Public Class Billet

Dim _num1, _num2, _num3, _num4, _num5, _num6 As Integer
Dim rand As Random

Sub New(ByVal _num1 As Integer, ByVal _num2 As Integer, ByVal _num3 As Integer, ByVal _num4 As Integer, ByVal _num5 As Integer, ByVal _num6 As Integer)
    Me.Num1 = _num1
    Me.Num2 = _num2
    Me.Num3 = _num3
    Me.Num4 = _num4
    Me.Num5 = _num5
    Me.Num6 = _num6
End Sub

Public Property Num1() As Integer
    Get
        Return _num1
    End Get

    Set(ByVal Value As Integer)
        _num1 = Value
    End Set
End Property

Public Property Num2() As Integer
    Get
        Return Num2
    End Get

    Set(ByVal Value As Integer)
        _num2 = Value
    End Set
End Property

Public Property Num3() As Integer
    Get
        Return _num3
    End Get

    Set(ByVal Value As Integer)
        _num3 = Value
    End Set
End Property

Public Property Num4() As Integer
    Get
        Return Num4
    End Get

    Set(ByVal Value As Integer)
        _num4 = Value
    End Set
End Property

Public Property Num5() As Integer
    Get
        Return _num5
    End Get
    Set(ByVal value As Integer)

    End Set
End Property

Public Property Num6() As Integer
    Get
        Return _num6
    End Get
    Set(ByVal value As Integer)

    End Set
End Property

Public Overrides Function ToString() As String
    Return "[" + Num1 + "]"   <----- ERROR :Invalid CastException : La conversion de la chaîne "[" en type 'Double' n'est pas valide.
End Function

End Class

Imports System.Random
Imports Microsoft.VisualBasic.FileIO
Imports System.IO


Public Class Simulation
Dim tabBillet As New ArrayList
Dim billetGagnant(5) As Integer

Sub GenerateBillet(ByVal nbmin As Integer, ByVal nbmax As Integer)
    Randomize()

    Dim value As Integer = CInt(Int((nbmax * Rnd()) + nbmin))

    For i As Integer = 0 To value
        For j As Integer = 0 To 6
            Dim num As Integer = CInt(Int((49 * Rnd()) + 1))
            tabBillet.Add(New Billet(num, num, num, num, num, num))
        Next
    Next

    ecrireFic(tabBillet)

End Sub

Function GenerateGagnant()
    Randomize()

    For i As Integer = 0 To 5
        Dim numero As Integer = CInt(Int((49 * Rnd()) + 1))
        billetGagnant(i) = numero
    Next
    Return billetGagnant
End Function

Public Sub ecrireFic(ByVal tabBillet As ArrayList)
    Dim path As String = "H:\test.txt"
    Dim sw As StreamWriter

    If File.Exists(path) = False Then
        sw = File.CreateText(path)
    End If

    sw = File.AppendText(path)
    For i As Integer = 0 To 3
        sw.WriteLine(tabBillet.Item(i).ToString())
    Next
    sw.Flush()
    sw.Close()

    ' Open the file to read from.'
    Dim sr As StreamReader = File.OpenText(path)
    Dim s As String
    Do While sr.Peek() >= 0
        s = sr.ReadLine()
        Console.WriteLine(s)
    Loop
    sr.Close()
End Sub

End Class

4 个答案:

答案 0 :(得分:0)

您可以拥有类似

的内容
Dim rnd As New Random()
Dim b As New Billet(rnd.Next(49), rnd.Next(49), rnd.Next(49), rnd.Next(49), rnd.Next(49), rnd.Next(49))

创建每个Billet对象。

答案 1 :(得分:0)

您应该使用&符号(&)进行字符串连接。 double上的+运算符会尝试将String转换为double,而不是像您期望的那样将double转换为String。所以它试图添加 "["(显然不是数字)到Num1。因此InvalidCastException

您的代码应为:

Return "[" & Num1 & "]"

答案 2 :(得分:0)

通用彩票

Private Sub Button1_Click(sender As System.Object, _
                          e As System.EventArgs) Handles Button1.Click

    Dim myLotto As New Lottery(49) 'fill the hopper
    myLotto.Draw(6) 'draw the balls
    Debug.WriteLine(myLotto.ToString) 'get the results

    'OR get the results one item at a time
    For x As Integer = 0 To myLotto.Count - 1
        Debug.WriteLine(myLotto.Item(x))
    Next
End Sub

Class Lottery
    Private Shared PRNG As New Random
    Private _theHopper As List(Of Integer)
    Private _draw As List(Of Integer)

    Public Sub New(maxNumber As Integer)
        Me.MaxNumber = maxNumber
        Me._theHopper = New List(Of Integer)
        Me._theHopper.AddRange(Enumerable.Range(1, Me.MaxNumber).ToArray)
    End Sub

    Private _maxNumber As Integer
    Public Property MaxNumber() As Integer
        Get
            Return Me._maxNumber
        End Get
        Set(ByVal value As Integer)
            Me._maxNumber = value
        End Set
    End Property

    Public Sub Draw(numberOfBalls As Integer, _
                    Optional DuplicatesAllowed As Boolean = False)
        Me._draw = New List(Of Integer)
        Dim whichNum As Integer
        For ct As Integer = 1 To numberOfBalls
            whichNum = PRNG.Next(Me._theHopper.Count)
            Me._draw.Add(Me._theHopper(whichNum))
            If Not DuplicatesAllowed Then Me._theHopper.RemoveAt(whichNum)
        Next
    End Sub

    Public Overrides Function ToString() As String
        If Me._draw Is Nothing Then
            Return Nothing
        Else
            Dim sb As New System.Text.StringBuilder
            For Each num As Integer In Me._draw
                sb.Append(num)
                sb.Append(" ")
            Next
            Return sb.ToString
        End If
    End Function

    Public ReadOnly Property Count() As Integer
        Get
            Return Me._draw.Count
        End Get
    End Property

    Public Function Item(itemNum As Integer) As Integer
        Return Me._draw(itemNum)
    End Function
End Class

答案 3 :(得分:0)

这是根据维基的彩票概念完成的

Public Class LotteryNum

    'This class create a set of lottery numbers in one group. 
    'Rule #1: Each number is from 1 to 49. 
    'Rule #2: No duplicates. 
    'Rule #3: Not ordered.
    'Rule #4: In one group. (No Mega Ball number)
    'Reference: http://en.wikipedia.org/wiki/Lottery

    Private Shared rand As New Random
    Private m As Integer = 5
    Private LowLimit As Integer = 1
    Private HighLimit As Integer = 49
    Private mNums As List(Of Integer)

    Sub New()
        Dim n As Integer
        mNums = New List(Of Integer)
        Do While mNums.Count <= m
            n = LowLimit + rand.Next(HighLimit - LowLimit + 1)
            If Not (mNums.Contains(n)) Then
                mNums.Add(n)
            End If
        Loop
    End Sub

    Sub New(ByVal GivenNums As Integer())
        If (GivenNums.Length <> 6) Then
            MsgBox("Input Lottery must contain 6 numbers ")
            Exit Sub
        End If

        mNums = New List(Of Integer)
        For Each n As Integer In GivenNums
            mNums.Add(n)
        Next
    End Sub

    Public ReadOnly Property Nums() As List(Of Integer)
        Get
            Return mNums
        End Get
    End Property

    Public Overrides Function ToString() As String
        Dim str As New List(Of String)
        For Each n As Integer In Nums
            str.Add(n.ToString)
        Next
        Return String.Join(", ", str.ToArray)
    End Function
    Public Shared Operator =(ByVal Lot1 As LotteryNum, ByVal Lot2 As LotteryNum) As Boolean
        For Each n1 As Integer In Lot1.Nums
            If Not (Lot2.Nums.Contains(n1)) Then
                Return False
            End If
        Next
        Return True
    End Operator
    Public Shared Operator <>(ByVal Lot1 As LotteryNum, ByVal Lot2 As LotteryNum) As Boolean
        Return Not (Lot1 = Lot2)
    End Operator

End Class

导入System.IO 模块模块1

Sub Main()
    Dim lot1 As New LotteryNum
    Dim given As New LotteryNum(New Integer() {10, 18, 25, 33, 42, 7})
    Dim myNum As New LotteryNum(New Integer() {10, 25, 33, 42, 18, 7})
    Dim yourNum As New LotteryNum(New Integer() {10, 23, 33, 42, 18, 7})

    Console.WriteLine("The new lottery numbers are: {0}", lot1.ToString)
    Console.WriteLine("My lottery is the LOTTERY: {0}", (myNum = given))
    Console.WriteLine("Your lottery is the LOTTERY: {0}", (yourNum = given))

    'Generate 300 lotteries and write to file
    Dim str As New List(Of String)
    For i As Integer = 0 To 299
        str.Add((New LotteryNum).ToString)
    Next
    File.WriteAllLines("c:\temp\lottery.txt", str.ToArray)


    Console.ReadKey()

End Sub

结束模块