简体   繁体   中英

java string index out of bounds

I have gone over and over this code and can't see where this is happening it doesn't happen every time it only happens if I run through post twice but I have tried getting rid of each of these in turn by commenting them out and that still gives the error but if I get rid of both my code works fine but they are necessary and they did work before. Any help is appreciated.

if(lines[i].length() > 10)
{
    if(lines[i].charAt(4) == '-' && lines[i+1].charAt(4) == '-')
    {
        lines[i] = "\nComment";
    }
}
if(lines[i].length() > 10)
{
    if(lines[i].charAt(4) == '-' && lines[i+1].charAt(4) != '-' && !lines[i-1].equals("\nComment"))
    {
        lines[i] = "\nPost";
    }
}

Your code does not check

  • that lines[i+1] exists,
  • that lines[i-1] exists, and
  • that the length of lines[i+1] is at least five.

This would break when i is zero or lines.length-1 , or when one of the prior/next lines has less than five characters.

lines[i+1].charAt(4) :如果lines[i+1]少于5个字符怎么办?

您只测试了lines[i]的长度,而您正在访问lines[i+1].charAt(4) ,如果长度小于5,则可能会出现此问题。

Check the length of all of your variables before using them. You vary the index but you don't do the neccesary checks (null, length and array index checks).

In particular when accessing:

lines[i+1]

and

lines[i-1]

我们确定+1和-1行是否在10个字符范围内?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM