【发布时间】:2020-10-10 22:31:29
【问题描述】:
/**
* Gets the initials of the name .
*
* @return the initials of the name.
*/public String initials()
{
String result = name.substring(0, 1);
for (int i = 0; i < name.length() - 1; i++)
{
if(name.charAt(i) == ' ')
{
result.concat(String.valueOf(name.charAt(i + 1)));
}
}
return result;
}
下面的测试器在调用initials方法后只返回'J':
Name name = new Name("John Jacob Jingleheimer Schmidt");
System.out.println(name.initials());
System.out.println("Expected: JJJS");
我这样写代码的时候,后面的char转换成String后还是不能concat结果后,只返回名字的第一个字母。
【问题讨论】:
-
请添加适当的标签以表明您使用的语言。另外,分享足够多的代码,以便其他人能够理解您面临的问题。
-
你通常应该使用
+来连接字符串,而不是concat(..)方法。