0

我正在尝试检查两个字符在 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。

任何帮助将不胜感激!

4

1 回答 1

1

你的for循环是这样说的:

for (int firstCheck = 0; firstCheck <= firstIndex.length(); firstCheck++)

问题是中间的陈述,firstCheck <= firstIndex.length(). 循环将以firstCheck等于运行firstIndex.length()。然后,当你使用时firstIndex.charAt(firstCheck),它会超出范围,因为字符串是零索引的,所以在等于字符串长度的位置没有字符。您可以像这样修复它:

for (int firstCheck = 0; firstCheck < firstIndex.length(); firstCheck++)
于 2015-03-19T23:56:04.600 回答