0

I am writing a simple program to get the first initial of the last name.

input: Bruce Lee
output: L

Here is the code:

public char getFirstInitial()
    {
        char initial;
        int num = this.getFullName().length();

        while (this.getFullName().charAt(num) != ' ')  //this is line 120
        {
                num--;
        }
        initial = this.getFullName().charAt(num + 1);

        return initial;
    }


public String getFullName()
    {
        return fullName;
    }

I'm getting this error:

java.lang.StringIndexOutOfBoundsException: String index out of range: 11
    at java.lang.String.charAt(Unknown Source)
    at lab1.Person.getFirstInitial(Person.java:120)

I don't get what the problem is. Thank you

1
  • int num = this.getFullName().length()-1; Also you can read the doc of charAt. "Returns the char value at the specified index. An index ranges from 0 to length() - 1" Commented Feb 16, 2014 at 17:55

4 Answers 4

2

Don't forget indexes are 0 based. So the first element is at index 0 and last is at lenght -1

You could also check for the index being >= 0 in that loop, in case the specified name is invalid.

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

1 Comment

Thanks!! solved it by adding -1 int num = this.getFullName().length() - 1;
1

Change

int num = this.getFullName().length();

to

int num = this.getFullName().length() - 1;

As indexes start from 0 and go till string.length()-1.

Comments

0

name.charAt(num) will throw the exception bcoz index will be 1 less than total length .

Update the code

while (name.charAt(num-1) != ' ')  //this is line 120
        {
                num--;
        }

Comments

0

In java there are always problems arisses when you perform index wise operations on a string therefore firstly you should convert the stricng into character array then you should perform operations, as the others described above if you use length()-1 instead of length() then array out of bounds error would be remove.

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.