import java.util.Scanner;
public class BF {
public static void main(String[] args) {
String S = new String(); //主串S
String T = new String(); //模式串T
int pos;
int result;
Scanner console = new Scanner(System.in);
S = console.nextLine();
T = console.nextLine();
pos = console.nextInt();
System.out.printf("%s\n", S);
System.out.printf("%s\n", T);
System.out.printf("%d\n", pos);
result = Index(S, T, pos);
System.out.printf("%d\n", result);
}
private static int Index(String S, String T, int pos){
int i = pos;
int j = 1;
while(i <= S.length() && j <= T.length()){
if(S.charAt(i) == T.charAt(j)){ //char.At方法是取出字符串中的字符
i++;
j++;
}
else{
i = i-j+2;
j = 1;
}
}
if(j > T.length()){
return i-T.length();
}
else{
return 0;
}
}
}
你这个是角标越界异常。i <= S.length() && j <= T.length()是有问题的,字符串角标是从0开始的,所以你要改成i < S.length() && j <T.length()或者
i <= S.length()-1 && j <= T.length()-1就可以了
数组下标越界了,你的数据没有chatAt(5)
你的i是从1开始的 , length是从1开始的,你最后一个数据就是charAt(5),但是charAt()是从0开始的只有0到4,
将《=改为《就好了