能否帮忙看一下关于String index out of range: -1的错误

这是一个Java的管理系统,其中有一个模块无法使用,提示出现String index out of range:-1的问题。
不知道是不是这句出现了问题,我的经验不太多。
<A href="<%=basePath%>newsinfo.jsp?id=<%=allnew.get(0).toString()%>" ><%=allnew.get(1).toString()%></A>
不知如何解决。请大神指点一下,谢谢!

给出的代码只会出现异常java.lang.IndexOutOfBoundsException: Index: 0, Size: 0,但是你的是

String index out of range: -1,这个是说字符索引越界了。给你两个例子说明:

&#8205;

    java.lang.IndexOutOfBoundsException: Index: 0, Size: 0

     

    import java.util.ArrayList;
    import java.util.List;
    public class Test {
     public static void main(String[] args) {
      List<String> list = new ArrayList();
      list.get(0);
    //  String str = "abc";
    //  str.substring(4);
     }
    }

    结果:

     

    2、java.lang.StringIndexOutOfBoundsException: String index out of range:-1

    import java.util.ArrayList;
    import java.util.List;
    public class Test {
     public static void main(String[] args) {
    //  List<String> list = new ArrayList();
    //  list.get(0);
      String str = "abc";
      str.substring(4);
     }
    }

    结果:

    上面的str.substring(4)里面的4改成5,-1就变成-2了。

    上面可以看出出现你那个错误就可能是你的某个地方对字符串进行了操作。一般如果在jsp页面用了substring这个函数可能出现。如果不是这个函数的问题,你可以用、StringIndexOutOfBoundsException这个类名在String类源码里面搜索下,可以看到有哪几个函数会抛出这个异常。比如下面的代码是String类里面的charAt函数:

        public char charAt(int index) {
            if ((index < 0) || (index >= count)) {
                throw new StringIndexOutOfBoundsException(index);
            }
            return value[index + offset];
        }

    如果在操作字符串的时候你没有胡乱的指定索引,即比如charAt函数,一般不会指定负数这样的索引,所以不会出现上面的异常值-1,按惯例来看,String 里面只有三个(重载不算)会异常值为负数的情况。而这三个也就substring比较常用.代码如下:

     public String substring(int beginIndex, int endIndex) {
     if (beginIndex < 0) {
         throw new StringIndexOutOfBoundsException(beginIndex);
     }
     if (endIndex > count) {
         throw new StringIndexOutOfBoundsException(endIndex);
     }
     if (beginIndex > endIndex) {
         throw new StringIndexOutOfBoundsException(endIndex - beginIndex);
     }
     return ((beginIndex == 0) && (endIndex == count)) ? this :
         new String(offset + beginIndex, endIndex - beginIndex, value);
        }

     

    如果确实是substring函数的问题,请在jsp页面下使用struts2标签或者c标签等判断下字符串的长度在进行截取。

     

    如含有问题,可以给我发邮箱[email protected]

    温馨提示:答案为网友推荐,仅供参考
    第1个回答  2020-12-19