<分区>
您如何将字符串缓冲区的功能转换为字符串生成器。我知道这两者非常相似,但我无法将 StringBuffer sb = new StringBuffer();
更改为 StringBuilder sb = new StringBuilder();
错误信息。
这是我编写的一些代码:
StringBuffer sb = new StringBuffer(); //Create a new String Buffer with nothing in it
for (int n = 0; n < 1; n++) {
sb.append("Billy "); //Add (first name)
sb.append("Scranner"); //Add (surname)
System.out.println(sb); //Print the string buffer
sb.insert(5," D"); //Insert " D" at the 4th character
System.out.println(sb); //Print the String Buffer with the middle initial
sb.delete(5, 7); //Delete the character line from 4 to 6
sb.reverse(); //Reverse the String Buffer
System.out.println(sb); //Print the reversed String Builder
如果我的问题看起来不清楚,我深表歉意,TLDR;我想知道如何使用 String Builder 而不是 String Buffer 获得与该程序相同的输出。
程序输出如下:
Billy Scranner
Billy D Scranner
rennarcS ylliB
编辑:这是我用 Builder 替换 Buffer 时得到的输出:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method append(String) is undefined for the type StringBuilder
The method append(String) is undefined for the type StringBuilder
The method insert(int, String) is undefined for the type StringBuilder
The method delete(int, int) is undefined for the type StringBuilder
The method reverse() is undefined for the type StringBuilder