我有以下方法,当单词是“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);
答案 0 :(得分:6)
看看你的循环条件;它在j < words.length
的条件下循环。您正尝试访问j+1
处的元素,导致其抛出IndexArrayOutOfBoundsException
。您需要将j < words.length
更改为j < words.length-1
,或者使用其他方法来完成您要完成的任务。