我正在编写一个简单的程序,以获得姓氏的第一个首字母。
input: Bruce Lee
output: L
以下是代码:
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;
}我得到了一个错误:
java.lang.StringIndexOutOfBoundsException: String index out of range: 11
at java.lang.String.charAt(Unknown Source)
at lab1.Person.getFirstInitial(Person.java:120)我不明白问题出在哪里。谢谢
发布于 2014-02-16 17:56:46
不要忘记索引是基于0的。因此,第一个元素位于索引0,最后一个元素位于伦特-1。
如果指定的名称无效,还可以在该循环中检查索引是否为>= 0。
发布于 2014-02-16 18:00:12
变化
int num = this.getFullName().length();至
int num = this.getFullName().length() - 1;作为索引,从0开始,一直到string.length()-1。
发布于 2014-02-16 18:01:05
name.charAt(num)将抛出异常bcoz索引,它将比总长度少1。
更新代码
while (name.charAt(num-1) != ' ') //this is line 120
{
num--;
}https://stackoverflow.com/questions/21815102
复制相似问题