日期:2014-05-20  浏览次数:20933 次

关于substring(begin,end)的问题
Java code
import java.util.Scanner;
public class homework3 {
    public static void main(String[] args){
        Scanner sc=new Scanner(System.in);
        System.out.println("输入一段字符:");
        String words=sc.next();
        System.out.println("输入要查找的字符串:");
        String toBeFound=sc.next();
        int[] index=new int[10];                 //存放下标位置的数组index
        int count=0;                             //index数组元素下标计数
        if(toBeFound.length()==1){
            for(int i=0;i<words.length();i++){   //如果输入的是字符
                if(words.substring(i,i+1).equals(toBeFound)){
                    index[count]=i;
                    count++;
                }
            }
        }else if(toBeFound.length()>1){
            for(int i=0;i<words.length();i++){   //如果输入的字符串且长度>1
                if(words.substring(i,i+toBeFound.length()).equals(toBeFound)){//26行错误
                    index[count]=i;
                    count++;
                }
            }
        }
        System.out.println("“"+toBeFound+"”"+"出现的位置是:");
        for(int i=0;i<index.length;i++){
            if(index[i]!=999999999){            //未赋新值的index中的元素消去
                System.out.print(index[i]+" ");
            }
        }
    }
}


运行结果:输入一段字符:
wojioushiwo
输入要查找的字符串:
wo
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 12
at java.lang.String.substring(String.java:1934)
at homework3.main(homework3.java:26)

java.lang.String.substring(String.java:1934)点进去看,拖黑的数据是:

if (endIndex > count) {
throw new StringIndexOutOfBoundsException(endIndex);
}

各位帮小弟看下,是哪里出错了

------解决方案--------------------
i+toBeFound.length()=12了 应该报错了吧