我被要求为String
编写“indexOf”方法。该方法获取字符串和子字符串。并返回子字符串出现的索引(如果有的话)。
但我一直收到这个错误:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 115
at java.lang.String.charAt(String.java:658)
at Strings.substring(Strings.java:132)
at Strings.indexOf(Strings.java:153)
at Strings.main(Strings.java:70)
这是我的代码:
//Calling Int indexOf() method:
//getting a new string and a substring from the user
System.out.println("Please enter a new string");
str4 = scan.nextLine();
System.out.println("Please enter a new substring");
str4Sub = scan.nextLine();
int test = indexOf(str4, str4Sub);
if (test != -1){
System.out.println("Your substring appeared first on place "
+ indexOf(str4, str4Sub) + "on your string");
}
else{
System.out.println("Sorry, your substring doesnt appear in "
+ "the given string");
}
}
/*
* Tests whether the two given string are the same.
* Returns true if the strings are equal,false otherwise.
*/
public static boolean isEqual(String s1, String s2){
int str1_length = s1.length(); //saves the length of the first string
int str2_length = s2.length();; //saves the length of the first string
boolean equal = true;
int i = 0;
//checking whether the length of both strings is the same
if (str1_length == str2_length) {
while (i != str1_length){
if (s1.charAt(i) == s2.charAt(i)){ //checking if the chars at
//places i on both strings are
//the same
i++;
equal = true;
}
else{
equal = false;
break;
}
}
}
else{
equal = false;
}
return equal;
}
/*
* Returns a new substring of string 'S',from place 'index' and in length
* of length'
* Returns String, newStr
*/
public static String substring(String s, int index, int length){
String newStr = ""; //will save the new string returned
//copying the new string in length of the given length
while (length != 0){
newStr += s.charAt(index);
index++;
length--;
}
return newStr;
}
/*
*Returns the index of the first appearance within the string s
*of the substring sub.
*Returns Integer, i.
*/
public static int indexOf(String s, String sub){
int i = 0;
boolean flag = false;
String strTmp = "";
while (i < s.length() && ( (s.length() - i )> sub.length() ) ){
strTmp = substring(s, s.charAt(i), sub.length());
System.out.println(strTmp);
if (isEqual(strTmp, sub)){
flag = true;
break;
}
else{
i++;
flag = false;
}
}
if (!flag){
i = -1;
return i;
}
else{
return i;
}
}
}
答案 0 :(得分:0)
在indexOf
,你写了
strTmp = substring(s, s.charAt(i), sub.length());
其中substring
的第二个参数实际上是int
。因此,i
位置s
处的字符在传递给此方法时会转换为int
。这将是一个比你预期的更大的数字。根据角色的内容以及String
的长度,它很可能会为您提供StringIndexOutOfBoundsException
。
您应该将该行更改为
strTmp = substring(s, i, sub.length());