0

Can any one help me? I do not understand this exception:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 9
    at java.lang.String.charAt(Unknown Source)
    at charPerLine.main(charPerLine.java:13)

Here's the code responsible:

import java.util.*;
public class charPerLine {

    public static void main(String[] args)throws StringIndexOutOfBoundsException {
        Scanner sc=new Scanner(System.in);
        System.out.print("Type any name:");
        String s=sc.next();
        int j= s.length()+1;
        for(int i=0;i<=j;i++){
            System.out.println(s.charAt(i));
        }
    }
}
1
  • 3
    You are accessing further than your string length. You need to post some code to let us understand why. Commented Mar 6, 2011 at 8:51

7 Answers 7

9

You're trying to directly access the 10th character of a string which has less than 10 characters. Something like:

"12345".charAt(9)

Remember that String indices are 0-based, hence .charAt(9) => 10th character. So "123".charAt(3) would throw, too.

Sign up to request clarification or add additional context in comments.

2 Comments

Very true, common cause is such loop for (i = 0; i <= length; i++) the = will cause that error..
Which is why we have for (char c : "123".toCharArray()) {...} :)
3

You are referencing a character at position 9, which is outside the range of the actual string. Remember to check that it's within the range [0, length[.

Comments

3

Ah. Thanks to Greg for spotting the link to the other half of this question. He is right, it isn't fair.

Your for loop goes from 0 to whatever the length of s is plus one.

So if s was an array:

['a','b','c']

Then it would go from 0 to 4. The indexes of that array are 0, 1 and 2. So you are trying to access two point beyond the end.

You want to remove this line:

int j= s.length()+1;

And change the for loop to:

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

Comments

2

j is s.length()+1 and then i is <=j. So: s.charAt(i) will eventually access index length()+1, which is 2 more than it is allowed to.

Comments

1

The loop should be:

for(int i=0; i < s.length(); i++){
  System.out.println(s.charAt(i));
}

The last character in the string has index:

s.length() - 1

so you need to use the guard:

i < s.length()

This way your loop terminates before i becomes s.length().

Comments

1

The expression

s.charAt(i)

will throw an error, if i is larger or equal than s.length(). Try using

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

instead.

Comments

0

just replace the

int j= s.length()+1;
for(int i=0;i<=j;i++){
 ...
}

with

int j= s.length();
for(int i=0;i<j;i++){
 ...
}

:)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.