kiddl
kiddl

Reputation: 3

Change labels every second based on a random number calculation

Here is the code I have so far. When I start nothing happens. I want the labels to change the text they are displaying every second. The text displayed should be a random number based on an equation. Thank you!

Public Class Form1
    Sub RandomValueFinder()
        Do

            Dim RandomNumber As Decimal
            RandomNumber = Int((1 * Rnd()) - 0.5)

            Dim RandomValuePH As Decimal = 7.3 + (0.8 * RandomNumber)
            Dim RandomValueTemp As Decimal = 95 + (7 * RandomNumber)
            Dim RandomValueFlow As Decimal = 1200 + (100 * RandomNumber)
            Dim RandomValuePressure5 As Decimal = 5 + (2 * RandomNumber)
            Dim RandomValuePressure20 As Decimal = 20 + (2 * RandomNumber)

            LabelPH.Text = RandomValuePH
            LabelTemp.Text = RandomValueTemp
            LabelFlow.Text = RandomValueFlow
            LabelPressure5.Text = RandomValuePressure5
            LabelPressure20.Text = RandomValuePressure20

        Loop
    End Sub

End Class

Upvotes: 0

Views: 66

Answers (1)

David
David

Reputation: 6131

I have a couple of notes.

First off, you are never calling your RandomValueFinder method so the code will never run.

Secondly, you currently update the labels via a Do/Loop. What would wind up happening if you did call your method is that it would go into an infinite loop that ties up the UI which would essentially "freeze" your form.

Thirdly, the parenthesis in your expressions aren't required because of PEMDAS/BODMAS.

Finally, do not use Int() or Rnd(), they are legacy holdovers.

I would suggest using a timer and calling your method in the appropriate method:

Public Class Form1

    Private ReadOnly _random As Random
    Private Readonly _timer As Forms.Timer

    Sub New()
        InitializeComponent()

        _random = New Random()
        _timer = New Forms.Timer() With { .Interval = 1000 } ' 1000ms = 1s
        AddHandler _timer.Tick, AddressOf Timer_Tick
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        _timer.Start()
    End Sub

    Private Sub Timer_Tick(sender As Object, e As EventArgs)
        RandomValueFinder()
    End Sub

    Sub RandomValueFinder()
        Dim RandomNumber As Decimal = 1 * _random.Next() - 0.5
        Dim RandomValuePH As Decimal = 7.3 + 0.8 * RandomNumber
        Dim RandomValueTemp As Decimal = 95 + 7 * RandomNumber
        Dim RandomValueFlow As Decimal = 1200 + 100 * RandomNumber
        Dim RandomValuePressure5 As Decimal = 5 + 2 * RandomNumber
        Dim RandomValuePressure20 As Decimal = 20 + 2 * RandomNumber

        LabelPH.Text = RandomValuePH
        LabelTemp.Text = RandomValueTemp
        LabelFlow.Text = RandomValueFlow
        LabelPressure5.Text = RandomValuePressure5
        LabelPressure20.Text = RandomValuePressure20
    End Sub

End Class

Upvotes: 1

Related Questions