线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:-1

时间:2011-02-04 06:21:48

标签: java string substring

 public static String s1 = "team A won the match historically to clinch series which made surprise around the world ";
 public static String s2 = "He did his part";

 t1=s1.length();
 t2=s2.length();
 t3=Math.abs(t1-t2); 

  for(i=0;i<t3;i++)
  {
      Sub_string.add(s1.substring(i,t2++));
  }

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:1)

试了一下。似乎没有抛出异常

我猜你的名单定义为最大尺寸?如果你这样定义它会起作用。

public class TestCode {
    public static String s1 = "team A won the match historically to clinch series which made surprise around the world ";
     public static String s2 = "He did his part";
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
         ArrayList<String> Sub_string = new ArrayList<String>();  

        int t1=s1.length();
        int t2=s2.length();
        int t3=Math.abs(t1-t2); 


        try {
            for(int i=0;i<t3;i++)
              {
                  Sub_string.add(s1.substring(i,t2++));
              }
        } catch (Exception e) {
            System.err.println();

        }

    }

}

答案 1 :(得分:1)

使用您提供的输入字符串从您的伪代码派生的代码不会抛出任何异常。

当调用 substring 并使用beginIndex(在您的情况下 i )大于endIndex时,抛出您发布的异常(StringIndexOutOfBoundsException:String index超出范围:-1) (在你的情况下 t2 )。

当您使用比 s2 短的 s1 调用代码时,您也会收到StringIndexOutOfBoundsException。

答案 2 :(得分:1)

以下代码可以满足您的目的...... 没问题。打印总和为73和设计师输出..;)  希望它有用!!!!

import java.util.ArrayList;
public class Trial {
    public static String s1 = "team A won the match historically to clinch series which made surprise around the world ";
     public static String s2 = "He did his part";

    public static void main(String[] args) {

         ArrayList<String> Sub_string = new ArrayList<String>();  

        int t1=s1.length();
        int t2=s2.length();
        int t3=Math.abs(t1-t2); 

        try {
            for(int i=0;i<t3;i++)
                  Sub_string.add(s1.substring(i,t2++));

        Object ia[] = Sub_string.toArray();
        for(int i=0; i<ia.length; i++)
            System.out.println(ia[i]);

        } catch (Exception e) {
            System.err.println();

        }

    }

}