线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:11 [英] Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
问题描述
EVerytime我写了类似于这个的任何代码,我得到了这种类型的错误。
它正在构建一个文件但不让它运行,它只是抛出异常。我不熟悉异常,因为我是初学者,请帮助我,并特别指出我正在犯的错误。
EVerytime I write any code similar to this one, I get this type of error. It's building a file but not letting it run, it just throws exception. I'm not familiar with exceptions as i am a beginner kindly help me out and specifically point out the mistake that I'm making.
public static void main(String args[]) {
String name = "Umer Hassan";
String name1 = "Hassan Umer";
char[] name2 = new char[name.length()];
for (int j = 0; j <= name.length(); j++) {
for (int i = 0; i <= name.length(); i++) {
if (name.length() == name1.length()) {
if (name.charAt(i) == name1.charAt(i)) {
name2[i] = name1.charAt(i);
}
}
}
}
}
当我运行程序时,它显示以下错误:
When I run the program it shows the following error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 11
at java.lang.String.charAt(String.java:658)
at Anagram.main(Anagram.java:24)
推荐答案
您的循环控制变量( i
/ j
)最高 name.length()
- 这是一个of bounds index(因为字符串/列表的最大索引是 len - 1
- 记住第一个索引是0)。
Your loop control variables (i
/ j
) are going up to name.length()
- which is an out of bounds index (since the max index of a string/list is len - 1
- remember the first index is 0).
尝试使用 i< name.length()
和 j< name.length
作为循环条件。
Try using i < name.length()
and j < name.length()
as the loop conditions instead.
这篇关于线程“main”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!