String index out of range: n

后端 未结 3 555
深忆病人
深忆病人 2021-01-26 16:55

Im having a bit of a problem with this code each time i execute it it gives me an error String index out of range: \'n\' n - is the no. of characters that is entered in the tex

相关标签:
3条回答
  • 2021-01-26 17:12

    Use <, not <= when iterating over the string. With <=, you get an out of bounds error, when j equals the length of the string. Remember that characters in the string are indexed starting from zero.

    for(int j = 0; j < b.length(); j++)
    
    0 讨论(0)
  • 2021-01-26 17:31

    In java string.charAt(string.length()) will be out of bounds since the string is 0 indexed and so the last character is at string.length() - 1.

    0 讨论(0)
  • 2021-01-26 17:31

    Strings are indexed starting at 0. Your second for loop is set to end at b.length, which will always be 1 greater than the highest index for that string., Change it to j < b.length instead.

    0 讨论(0)
提交回复
热议问题