我正在编写一个简短的Java脚本,其中我将字符串中的名称作为变量。我想编写 get 方法来获取缩写并返回它们以供以后使用。该方法在打印首字母缩写时效果很好,但在想要返回该值时效果不佳。
//method for getting initials of the name
public String getInitials() {
String words[] = competitorName.split(" ");
for(String word : words) {
return word.charAt(0) + " ";
}
}
它告诉我该方法必须返回 String 类型的结果,但这应该已经是它了。即使我添加 toString 方法(然后它写它已经是 String)也不起作用
最佳答案
你差点就明白了!只需使用 StringBuilder 并返回结果
public String getInitials() {
String words[] = competitorName.split(" ");
StringBuilder builder = new StringBuilder();
for(String word : words) {
builder.append(word.charAt(0));
}
return builder.toString();
}
关于java - 返回缩写的 Get 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58396257/