jeudi 29 juin 2023

Why does VB Random.Next appear misbehave when within an If or Case statement?

I have a snippet of code to select a string randomly from an array. It works fine, except it misbehaves when run within a select-case or If statement.

The following code gives me a random result for Petrol or Diesel, however I only ever get a return of "Electronic Injection Pump" when the randomly selected fuel is "Diesel", and I only get "Carburettor" or "Mechanical Fuel Injection" when the randomly selected fuel is "Petrol".

If I take the fuel system selection code out of the case statement it works as expected giving all the fuel system options. I have tried using an If statement but this gives the same flawed result. The .count values return their expected results of 2 and 3 respectively.

I'm really scratching my head because "Electronic Injection Pump" is second in it's array, while "carburettor" and "Mechanical Fuel Injection" are first and second in their array, so there seems no rhyme or reason to the faulty result.

Dim fuelLr = New Random()
        Dim fuelList() As String = {"Petrol", "Diesel"}
        Dim fuel = fuelList(fuelLr.Next(0, fuelList.Count))

        Dim fuelSystem
        Select Case fuel
            Case "Diesel"
                Dim dieselSystemLr = New Random()
                Dim dieselSystemList() As String = {"Mechanical Injection Pump", "Electronic Injection Pump"}
                fuelSystem = dieselSystemList(dieselSystemLr.Next(0, dieselSystemList.Count))

            Case "Petrol"
                Dim petrolSystemLr = New Random()
                Dim petrolSystemList() As String = {"Carburettor", "Mechanical Fuel Injection", "Electronic Fuel Injection"}
                fuelSystem = petrolSystemList(petrolSystemLr.Next(0, petrolSystemList.Count))

        End Select



Aucun commentaire:

Enregistrer un commentaire