B4J Question java.lang.StringIndexOutOfBoundsException

TorontoJim

Member
Licensed User
Longtime User
I'm having this problem, as a user was in an older post. I'm trying to build a string of random characters by concatenating random characters from a string of characters.

When I got the out of bounds exception, I started testing the values to see what was coming back. However, the values I'm getting are not out of range. This is the code:

B4X:
Dim strChars As String
strChars = "-abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%&*()"
Do While strWrite.Length < 1024
    intRandom = RandomNumber(0, strChars.Length - 1, False)
    strWrite = strWrite & strChars.SubString2(intRandom, 1)
Loop
        
Sub RandomNumber(Lowest As Int, Highest As Int, PreventZero As Boolean) As Int
    Lowest  = Round(Lowest)
    Highest = Round(Highest)
    If Lowest = Highest Then
        Return Lowest
    Else
        If Lowest > Highest Then
            Dim TempValue = Lowest As Int
            Lowest   = Highest
            Highest  = TempValue
        End If
        Dim ReturnValue = Lowest + Rnd(0, Highest - Lowest) As Int
        If ReturnValue = 0 And PreventZero Then
            Return RandomNumber(Lowest, Highest, PreventZero)
        Else
            Return ReturnValue
        End If
    End If
End Sub

The length of strChars is 72. The last four iterations of this the number generated was 55, 44, 9, 20. That means it was looking for:

B4X:
strWrite = strWrite & strChars.SubString2(55, 1)
strWrite = strWrite & strChars.SubString2(44, 1)
strWrite = strWrite & strChars.SubString2(9, 1)
strWrite = strWrite & strChars.SubString2(20, 1)

Those substring positions are all within the length of the strChars.
 

TorontoJim

Member
Licensed User
Longtime User
I just answered my own question. I was confusing B4J and another language. The substring is reading from start index to end index. I need to make the end index, the start index + 1, not 1.
 
Upvote 0
Top