这是我的代码:
public static void main(String[] args)
{
String teacherName = "Benjamin Brown";
int teacherSecondInitialIndex = (teacherName.indexOf(" ") + 1);
String teacherInitials = new StringBuilder(teacherName.charAt(0)).append(teacherName.charAt(teacherSecondInitialIndex)).toString();
System.out.println(teacherInitials);
}
我想打印出teacherName的首字母,这将是" BB"。但只有" B"正在打印出来。有什么问题?
答案 0 :(得分:4)
new StringBuilder(teacherName.charAt(0))
接受int
。因此,您传递的char
值正在被扩展并用作StringBuilder
容量,而不是基础char
中的第一个String
。
创建一个空的StringBuilder
并附加两个字符。
String teacherInitials = new StringBuilder()
.append(teacherName.charAt(0))
.append(teacherName.charAt(teacherSecondInitialIndex))
.toString();