Every now and then I get this error java.lang.IndexOutOfBoundsException: Invalid index 35, size is 35...and I am unsure of why. I generate 36 random numbers and then assign them to a listview...then pull them out of the listview like:
Sub GenerateLocations
LocationGenerator.Put(Rnd(1, 37), "") 'generate random number between 1 and 36
LocationGenerator.Put(Rnd(1, 37), "")
etc..
For i = 0 To LocationGenerator.Size - 1
ListView1.AddSingleLine(LocationGenerator.GetKeyAt(i))
Next
SetLocations
End Sub
a lot more than 36 times because for some reason it doesn't generate correctly to the map unless it is overdone. If you try this in a small test application you will see that it will only add a full list of random numbers 1-36 if you overdo the LocationGenerator.Put(Rnd(1, 37), "") line. Trying your code didn't output correctly for my app...but with tweaking (increasing the size of the loop) I got it working but that will most likely end up with the same error?
-----------
Edit: yeah same error tho I like that the code is much smaller in size
I guess it may be worth saying that it ALWAYS generates the first level properly and I think it does the second one as well, but somewhere down the line it just crashes it
I did some testing in the app. I added a label for Map.size and a label for ListView.size. I made a button that calls the event to randomize, etc. The labels both read 36 through a random amount of clicks then suddenly both drop to 35. I put together a test project showing what happens. Just open it and click the "Generate Button" until the error pops up.
The Map will only allow unique keys, so if you are using a random number generator you can guarantee that there are some duplicates that don't create an entry.
To ensure there are 36 entries you need to use a loop and either leave it to chance on how long it takes, or manipulate the data somewhat so that it only takes 36 tries.
B4X:
Do While LocationGenerator.Size < 36
LocationGenerator.Put(Rnd(1, 37), "")
Loop
That could take ages to fill it on a bad day.
Or you could do something like this which will fill the next available slot to the random number and take 36 iterations.:
B4X:
Do while LocationGenerator.Size < 36
Num=Rnd(1, 37)
Result=""
Do While Result = ""
If LocationGenerator.GetDefault(Num,"NotFound") = "NotFound" Then
LocationGenerator.Put(Num, "")
Else
Num=Num+1
'If the last number is filled send it back to the beginning
If Num = 37 Then Num = 0
End If
Loop
Loop
Yeah, I was counting on the unique key entry of the Map to pull a set of random numbers between 1-36 without any duplicates. I will test your posted code out. What should I Dim Result as?
Do While LocationGenerator.Size < 36
LocationGenerator.Put(Rnd(1, 37), "")
Loop
Completely solved the problem and doesn't cause any issues as far as I can see. Man you need to have a donate button under your name. You are an asset to this forum.