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
int num = this.getFullName().length()-1;Also you can read the doc ofcharAt. "Returns the char value at the specified index. An index ranges from 0 to length() - 1"