线程“main”中的exceptionjava.lang.StringIndexOutOfBoundsException:字符串索引超出范围:11
EVerytime我写了类似于这个的任何代码,我得到这种类型的错误。 它正在构建一个文件但不让它运行,它只是抛出exception。 我不熟悉exception,因为我是初学者,请帮助我,并特别指出我正在犯的错误。
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); } } } } }
当我运行该程序时,它显示以下错误:
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()
– 这是一个越界索引(因为字符串/列表的最大索引是len - 1
– 记住第一个索引是0)。
尝试使用i < name.length()
和j < name.length()
作为循环条件。
您应该将for循环写为
for (int i = 0; i < name.length(); i++)
字符串中的索引从零开始,如在数组中一样,因此它们的范围从0到length - 1.您将转到长度,这超出了边界。
for (int i=0; i<=name.length();i++){
字符串索引从0
开始。
示例:
String str = "abc"; int len = str.length(); //will return 3
str.charAt(3);
将抛出StringIndexOutOfBoundsException
charAt
起始位置为0
。 所以限制是length-1
。
你必须将for循环更改为for (int i=0; i
尝试这个:
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(j)) { name2[i] = name1.charAt(j); } } } }
}