Проблема исключения и случайное число - PullRequest
0 голосов
/ 28 марта 2011

Я делаю лотерею в VB.NET

Я получил ошибку, когда симулировал вещь.Чтобы записать в файл любую «заготовку», сгенерируйте ошибку:

Недопустимое исключение CastException было обработано: преобразование цепочки «[» в «Double» было недействительным

Кроме того, я не знаю, как сделать последовательность случайных чисел от 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 голосов
/ 29 марта 2011

Это сделано согласно концепции лотереи в вики

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

Конечный модуль

0 голосов
/ 28 марта 2011

Вы должны использовать амперсанды (&) для конкатенации строк. Оператор + в double пытается преобразовать String в double вместо того, чтобы преобразовывать double в String, как вы ожидаете. Поэтому он пытается добавить "[" (что, очевидно, не число) к Num1. Отсюда InvalidCastException.

Ваш код должен читать:

Return "[" & Num1 & "]"
0 голосов
/ 28 марта 2011

Общая лотерея

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
0 голосов
/ 28 марта 2011

У вас может быть что-то вроде

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.

...