Java 在检查数组时遇到问题
我应该在一个字符数组中搜索另一个字符数组。我遇到的问题是,我应该检查单词是否匹配。此外,当搜索词比原始字符串长时,我不断得到一个越界异常Java 在检查数组时遇到问题,java,arrays,string,char,indexoutofboundsexception,Java,Arrays,String,Char,Indexoutofboundsexception,我应该在一个字符数组中搜索另一个字符数组。我遇到的问题是,我应该检查单词是否匹配。此外,当搜索词比原始字符串长时,我不断得到一个越界异常 public int indexOf(String parameter) { //does same thing as previous method but with a String instead int index = -1; char charArray[] = parameter.toCharArray(); int cou
public int indexOf(String parameter) { //does same thing as previous method but with a String instead
int index = -1;
char charArray[] = parameter.toCharArray();
int counter = 0;
for (int i = 0; i < indexArray.length; i++) { //goes through the array and find which array element is = to the char
if (indexArray[i] == charArray[0]) { //checks if the index is equal to the first AND second letter of the word
for (int j = i; j < charArray.length; j++) {
if (indexArray[j] == charArray[j]) {// this is where the Exception java.lang.ArrayIndexOutOfBoundsException: 14 error happens
counter++;
}
if (counter == charArray.length) {
index = i;
return index;
}
}
}
}
return index;
}
charArray
是搜索词的数组。
索引数组是原始字符串的字符数组
public int indexOf(String parameter) { //does same thing as previous method but with a String instead
int index = -1;
char charArray[] = parameter.toCharArray();
int counter = 0;
for (int i = 0; i < indexArray.length; i++) { //goes through the array and find which array element is = to the char
if (indexArray[i] == charArray[0]) { //checks if the index is equal to the first AND second letter of the word
for (int j = i; j < charArray.length; j++) {
if (indexArray[j] == charArray[j]) {// this is where the Exception java.lang.ArrayIndexOutOfBoundsException: 14 error happens
counter++;
}
if (counter == charArray.length) {
index = i;
return index;
}
}
}
}
return index;
}
public int indexOf(String参数){//执行与前面方法相同的操作,但使用的是字符串
int指数=-1;
char charArray[]=parameter.toCharArray();
int计数器=0;
for(inti=0;i
说出indexArray是“葡萄”还是charArray是“菠萝”。在i=3
,indexArray[i]==charArray[0]
返回true。现在设置j=3
并检查直到j<9
,显然indexArray[j]
会给您一个ArrayIndexOutOfBoundsException
您应该将其更改为:
// There is no point to check indices that the subsequent string is shorter than the search string.
for (int i = 0; i < indexArray.length - charArray.length; i++) {
if (indexArray[i] == charArray[0]) {
for (int j = 0; j < charArray.length; j++) {
if (indexArray[i + j] == charArray[j]) {
// ...
}
}
}
}
//没有必要检查后续字符串是否比搜索字符串短。
对于(inti=0;i
Post stacktrace of.exception,以及在线程“main”java.lang.ArrayIndexOutOfBoundsException中抛出exceptionException的字符串:14完整stacktrace及其引用的行。线程“main”java.lang.ArrayIndexOutOfBoundsException中的异常:14位于MyString.indexOf(MyString.java:53)位于MyString.startsWith(MyString.java:74)mainsignment7.searchString(mainsignment7.java:108)和mainsignment7.main(mainsignment7.java:70)