首页 > 解决方案 > 如何修复“StringIndexOutOfBoundsException”错误?

问题描述

我需要制作一个程序来打印两个字符串中最长的公共子字符串。例如:

String str1 = "abcdef";
String str2 = "abcgef";

最长的公共字符串应该是"abc". 我只能使用循环、字符串和数组!没有方法/功能等。我是初学者,虽然我知道功能,但我不允许使用它。

我尝试使用计数变量,以便最后一个字母不会一遍又一遍地与第二个字符串中的其他字符进行比较,但会发生相同的错误。

String com = "";
String com2 = "";
int a;
int b;

for (i = 0; i < str1.length(); i++) {

    int count1 = 0;
    int count2 = 0;

    for (int j = 0; j < str2.length(); j++) {        
        a = i;
        b = j;
        com2 = "";

        while (str1.charAt(a) == str2.charAt(b)) {
            com2 = com2 + str1.charAt(a);                  

            if (com2.length()>com.length()) {              
                com = com2; 
            }     

            if (a<str1.length()-1) {       
                a++;  
            }

            if (b<str2.length()-1) {       
                b++;
            }                                   
        } 
    } 
} 

System.out.println(com);

就像我说的,结果应该是"abc"这样,但我得到一个运行时错误,说StringIndexOutOfBoundsException超出范围 6。

谢谢!

标签: javaruntime-error

解决方案


你有你的例外,因为你循环直到a<str1.length()b<str2.length()。您应该将其更改为a<str1.length()-1. 发生这种情况是因为您的字符串长度 = 6,但您从 0 开始。所以第 6 个元素将是 5。此外,while{}当您有无限循环时ab到达 and 的最后一个索引str1str2所以要小心。

附言

您可以将其更改为

public void method() {
    StringBuilder com = new StringBuilder();
    String str1 = "abcdef";
    String str2 = "abcgef";

    if (str1.length() == str2.length()) {
        for (int i = 0; i < str1.length() - 1; i++) {
            if (str1.charAt(i) == str2.charAt(i)) {
                com.append(str2.charAt(i));
                continue;
            } else {
                break;
            }
        }
        System.out.println(com);
    } else {
        System.out.println("They have different length");
    }
}

推荐阅读