获取返回首字母的方法
Get method for returning initials
我正在编写一个简短的 Java 脚本,其中我在字符串中有一个名称作为变量。我想写 get 方法来获取缩写和 return 它们以备后用。该方法在打印出首字母时效果很好,但在想要 return 该值时效果不佳。
//method for getting initials of the name
public String getInitials() {
String words[] = competitorName.split(" ");
for(String word : words) {
return word.charAt(0) + " ";
}
}
它告诉我该方法必须 return String 类型的结果,但应该已经是它了。即使我添加 toString 方法也不起作用(然后它写道它已经是 String)
你快明白了!只需使用 StringBuilder 和 return result
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 方法来获取缩写和 return 它们以备后用。该方法在打印出首字母时效果很好,但在想要 return 该值时效果不佳。
//method for getting initials of the name
public String getInitials() {
String words[] = competitorName.split(" ");
for(String word : words) {
return word.charAt(0) + " ";
}
}
它告诉我该方法必须 return String 类型的结果,但应该已经是它了。即使我添加 toString 方法也不起作用(然后它写道它已经是 String)
你快明白了!只需使用 StringBuilder 和 return result
public String getInitials() {
String words[] = competitorName.split(" ");
StringBuilder builder = new StringBuilder();
for(String word : words) {
builder.append(word.charAt(0));
}
return builder.toString();
}