Exception in thread “main” java.lang.StringIndexOu

2020-02-11 05:53发布

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)

标签: java string
4条回答
老娘就宠你
2楼-- · 2020-02-11 06:09

try this:

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);
            }
        }
    }
}

}

查看更多
Ridiculous、
3楼-- · 2020-02-11 06:11

You should write the for cycle as

for (int i = 0; i < name.length(); i++)

The indexes in the strings are zero-based, as in the arrays, so they have a range from 0 to length - 1. You go to length, which is outside of bounds.

查看更多
Luminary・发光体
4楼-- · 2020-02-11 06:20
for (int i=0; i<=name.length();i++){

String indexes are starting from 0 .

Example :

String str = "abc";
int len = str.length(); //will return 3

str.charAt(3); will throws StringIndexOutOfBoundsException charAt starting position is 0 . So the limit is length-1 .

You have to change your for loop to for (int i=0; i<name.length();i++){

查看更多
我命由我不由天
5楼-- · 2020-02-11 06:35

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).

Try using i < name.length() and j < name.length() as the loop conditions instead.

查看更多
登录 后发表回答