我正在尝试检查两个字符在 while 循环中是否相等,但是当我运行它时出现此错误:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:5 at java.lang.String.charAt(String.java:686) at Practice.main(Practice.java:27)
我的代码:
import java.util.Scanner;
public class Practice {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("String: ");
String firstIndex = input.next();
System.out.print("String Two: ");
String secondIndex = input.next();
int seqStart = -1;
int secCheck = 0;
int start;
if (firstIndex.length() >= secondIndex.length()) {
for (int firstCheck = 0; firstCheck <= firstIndex.length(); firstCheck++) {
if (firstIndex.charAt(firstCheck) != secondIndex.charAt(0)) {
continue;
}else if (firstIndex.charAt(firstCheck) == secondIndex.charAt(0)) {
start = firstCheck;
while (firstIndex.charAt(firstCheck) == secondIndex.charAt(secCheck)) {
for (int check = 0; secCheck < secondIndex.length(); check++) {
firstCheck++;
secCheck++;
if (check == secondIndex.length()) {
seqStart = start;
secCheck = (secondIndex.length() + 10);
}
}
}
}
}
}
System.out.println(seqStart);
}
}
该程序应该检查一个字符串是否包含在另一个字符串中,如果是,则返回第二个字符串在第一个字符串中开始的位置。如果不是,则返回 -1。
任何帮助将不胜感激!