【发布时间】:2015-05-23 07:16:54
【问题描述】:
我正在尝试在 while 循环中检查两个字符是否相等,但运行时出现此错误:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:5 在 java.lang.String.charAt(String.java:686) 在 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。
任何帮助将不胜感激!
【问题讨论】:
-
firstCheck <= firstIndex.length()应该是firstCheck < firstIndex.length()- Java (大部分)是零索引 -
做到了,但我仍然在第 27 行收到错误消息:while (firstIndex.charAt(firstCheck) == secondIndex.charAt(secCheck)) {
-
while (firstIndex.charAt(firstCheck) == secondIndex.charAt(secCheck))- 如果没有匹配的chars 会发生什么? -
它工作正常,返回-1
-
但是
for-loop完成后,firstCheck和secCheck设置为什么?您需要检查这些变量的状态...while (firstCheck < firstIndex.length() && secCheck < secondIndex.length() && firstIndex.charAt(firstCheck) == secondIndex.charAt(secCheck)) {