KNsiva
KNsiva

Reputation: 387

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1

 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++));
  }

How can I solve this?

Upvotes: 2

Views: 6242

Answers (3)

aman_novice
aman_novice

Reputation: 1037

The following code would serve your purpose... gives no problem. Prints sum as 73 and a designer output..;) Hope its helpful!!!!

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();

        }

    }

}

Upvotes: 1

Aba Dov
Aba Dov

Reputation: 962

tried it. doesn't seem to throw an exception

I guess you defined your list to have max size? if you define it like this it will work.

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();

        }

    }

}

Upvotes: 1

diciu
diciu

Reputation: 29333

Code derived from your pseudocode, with the input strings you provided, will not throw any exception.

The exception you posted (StringIndexOutOfBoundsException: String index out of range: -1) is thrown when substring is called with beginIndex (in your case i) larger then endIndex (in your case t2).

You will also get a StringIndexOutOfBoundsException when you call your code with a s1 that is shorter then s2.

Upvotes: 1

Related Questions