0

I have this code but it seems that the "randomChar" is unused variable.

        Dim validchars(3) As String 
        Dim i As Int
        validchars(0) ="+"
        validchars(1) ="-"
        validchars(2) ="*"


        Dim idx As Int = Rnd(0, validchars.Length) 
        Dim randomChar As String = validchars(idx)
Ikaros
  • 169
  • 2
  • 7
  • What do you do with `randomChar` after that one line? If the answer is "nothing", it's an unused variable (because you've not used it). The single line you've included does *not* use it, because it's just assigning a value and then doing nothing; you would get the exact same result by deleting that line of code entirely. – Ken White Apr 21 '15 at 13:23

3 Answers3

0

Hi Do you mean you are getting a compiler warning? If so and your code works then ignore it otherwise you could try setting the valid chars as one string and then substring2 the one you ant to reference.

John
  • 11
  • 2
0

Array index starts from zero (0) so if the random ie idx generates 3 technically it should be 2 in your array so with your current code, it will give error since 3 will not exist.

valid chars and their Array indexes (+ index is 0, - index is 1, * index is 2)

Fix subtract 1 from the idx, and also start the Rnd from 1

 Dim idx As Int = Rnd(1, validchars.Length)
Dim randomChar As String = validchars(idx - 1)

in this case if the idx(ie Random Generated number is 3, with the minus 1 it will equal 2 which is * and likewise if idx is 1 - 1 will be zero which is +

boluvisako
  • 51
  • 6
0

You will get a compiler warning (unused variable 'randomChar'), which you can ignore.

Rnd(min,max) goes from min (inclusive) to max (exclusive), so

Dim Int idx = Rnd(0,validchars.Length)  

the idx will go from 0 to (validchars.length-1). The following array access will always be valid. Your code will never crash.

Matti81
  • 216
  • 3
  • 3