-1

Im trying to do this programme

int contains(String s1, String s2): receives two strings, and checks whether s2 is in s1 case sensitively. If s2 is in s1 it returns the index of the last occurrence of s2, otherwise it returns -1.

Here is an example

Enter first string: O pikap, su pikap, bu pikap.
Enter second string: pikap
22
Enter first string: O pikap, su pikap, bu pikap.
Enter second string: pikapcik
-1

I've written the codes but gave me an error like this

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1
   at java.lang.String.charAt(Unknown Source)
   at Test.main(Test.java:12)**

Why there is such an error and how do i fix this? Im only allowed use charAt and length methods

Here is the code

public static void main(String[] args){
    String b1 = "O pikap, su pikap, bu pikap";
    String a1 = "pikap";
    String sum = "";
    int b =b1.length();
    int a =a1.length();
    for( ; b>0 ; b--){
        b = b - a;
        for(int n = 0; n < a ; n++ , b++){
            sum+= b1.charAt(b);
        }
        if(sum == a1)
            break;   
    }//for 1
    System.out.println(b-a+1);
}
M. Aktas
  • 131
  • 1
  • 3
  • 14
  • 2
    You fix this by not doing `b1.charAt(-1)`.. –  Nov 18 '16 at 12:40
  • 1
    Homework alert. – nicomp Nov 18 '16 at 12:42
  • Try looking [here](http://stackoverflow.com/questions/18446302/java-arraylist-got-java-lang-indexoutofboundsexception) or [here](http://stackoverflow.com/questions/21570318/understand-arraylist-indexoutofboundsexception-in-android) or any of the other hundreds of duplicates on this site. – takendarkk Nov 18 '16 at 12:43
  • 1
    Also note that strings **must** be checked for equality with `equals` not `==` –  Nov 18 '16 at 12:47

3 Answers3

0

because in loop for each decrements it's increasing for whole character and then StringIndexOutOfBoundsException exception occurs check b-- and b++ condition below:

for( ; b>0 ; b--){
    b = b - a;
for(int n = 0; n < a ; n++ , b++){
    sum+= b1.charAt(b);
}
if(sum == a1)
break;         }//for 1
mayank agrawal
  • 628
  • 5
  • 20
0

Uhm.. read documenation on the String object before starting on custom objects.

    String b1 = "O pikap, su pikap, bu pikap";
    String a1 = "pikap";
    System.out.println( b1.lastIndexOf(a1)  );

If you need to know how it works

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/lang/String.java#String.lastIndexOf%28char%5B%5D%2Cint%2Cint%2Cchar%5B%5D%2Cint%2Cint%2Cint%29

Tschallacka
  • 27,901
  • 14
  • 88
  • 133
0

You should stop the loop if int b is smaller than int a. When int b is decreased to 4 in the first loop the result of the operation b = b-a; means b = -1 and in second loop it checks b1.charAt(-1) and there is no -1. index of string b1. btw you can simply use str.lastIndexOf().

MNEkin
  • 46
  • 1
  • 5