英文:
.concat() is not working with String.valueOf
问题
/**
 * 获取姓名的缩写。
 *
 * @return 姓名的缩写。
 */
public String initials() 
{
   String result = name.substring(0, 1);
   for (int i = 0; i < name.length() - 1; i++)
   {
        if(name.charAt(i) == ' ')
        {
           result = 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");
在这种编码方式下,将转换后的字符连接到字符串后仍无法正常连接到结果,仅返回姓名的首字母。
英文:
/**
 * 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;
 }
The tester is below which only returns 'J' after calling the initials method:
Name name = new Name("John Jacob Jingleheimer Schmidt");
System.out.println(name.initials());
System.out.println("Expected: JJJS");
When I write the code in this way, the following char after converted to String still cannot concat after the result, and only returns the first letter of the name.
答案1
得分: 3
String是一个不可变类,即String#concat会创建一个新的String,你需要将其赋值回结果,如下所示:
result = result.concat(String.valueOf(name.charAt(i + 1)));
英文:
String is an immutable class i.e. String#concat creates a new String which you need to assign back to result as shown below:
result = result.concat(String.valueOf(name.charAt(i + 1)));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论