使用==(Java)检查两个字符是否相同

时间:2015-03-19 23:52:44

标签: java string char charat

我正在尝试检查while循环中两个字符是否相等但在运行时遇到此错误:

线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:5     at 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。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分: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++)