-2

我有以下方法,当单词是“sk”但不是“ks”时,它会给我一个错误。这些关键字来自 arrPunjabi。

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 7
at StringTes.main(StringTes.java:51)

HashSet<String> all = new HashSet<String>();
    String[] arrPunjabi = {"d b a b s k s", "d t r p n d k h"};
    String[] arrGurmukhi = {"fMfauiq bMdn Aink bwr srb klw smrQ ]", "foln qy rwKhu pRBU nwnk dy kir hQ ]1]"};
    ArrayList<String> arr = new ArrayList<String>();
    String word = "sk";
    char[] wordArr = word.toCharArray();
    for(int i = 0; i< arrPunjabi.length;i++){
        String[] words = arrPunjabi[i].split("\\s+");
        //word[] = {d, b, a, b, s, k, s};
     if (word.length() == 2){
            for(int j = 0; j < words.length; j++){
                if(words[j].startsWith(""+wordArr[0]) && words[j+1].startsWith(""+wordArr[1])){   //this is where I am getting an error.
                    arr.add(arrGurmukhi[i]);
                    all.addAll(arr);
                    arr.clear();
                    arr.addAll(all);
                }
            }
        }

    }
    System.out.println(arr);
4

1 回答 1

6

查看您的循环条件;它在 的条件下循环j < words.length。您正在尝试访问 处的元素j+1,导致它抛出IndexArrayOutOfBoundsException. 无论您想要完成什么,您都需要更改j < words.length或使用替代方法。j < words.length-1

于 2013-08-17T03:59:32.283 回答