java - 如何修复“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。
谢谢!
解决方案
你有你的例外,因为你循环直到a<str1.length()
和b<str2.length()
。您应该将其更改为a<str1.length()-1
. 发生这种情况是因为您的字符串长度 = 6,但您从 0 开始。所以第 6 个元素将是 5。此外,while{}
当您有无限循环时a
,b
到达 and 的最后一个索引str1
,str2
所以要小心。
附言
您可以将其更改为
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");
}
}
推荐阅读
- javascript - Formdata 正在显示文件,但 laravel 的请求显示为空
- typescript - 利用 typescript 类型系统来改进我的代码
- angular - .NET Core -> Angular - 在 MVC 中使用接口时数据丢失
- python - 类 ShareGUI 未定义
- c++ - 来自可变参数模板的 shared_ptr 元组?
- demo - 普通用户可以使用 cognician.com/my-data 为特定程序重置数据吗?
- python - 来自 keras 模型的访问损失指标
- vue.js - 如何在可用更新时提示 Vuejs pwa 应用程序中的用户?
- azure-ad-b2c - Azure B2C 自定义策略在实现基于组合的注册&登录和邀请 URL 的注册&登录时发生异常
- python - 创建包含月份日期的列表