我正在做一个计算机科学项目,我需要合并 StringBuffer
。我需要帮助了解 .append
的作用以及连接的含义。有人告诉我,我可以通过将 .append
与 StringBuffer
结合使用来显示谁是(我的游戏)的赢家。
public static void winner ()
{
if (position1 >= 100){
System.out.println("THE WINNER IS " + name1);
}
else if (position2 >= 100){
System.out.println("THE WINNER IS " + name2);
}
}
我可以使用 StringBuffer
来输出谁赢了比赛,而不是将名称作为字符串吗?
最佳答案
感谢编译器,您已经在使用 StringBuilder
,它是 StringBuffer
的更新、更快的版本。
您上面的代码将编译为等同于:
public static void winner ()
{
if (position1 >= 100){
System.out.println(new StringBuilder("THE WINNER IS ").append(name1).toString());
}
else if (position2 >= 100){
System.out.println(new StringBuilder("THE WINNER IS ").append(name2).toString());
}
}
因此,在这种情况下,您不会完成尚未为您完成的任何事情。在循环中构建 String
时使用 StringBuilder
。
在您的情况下,他们可能正在讨论为这两种情况预初始化单个 StringBuilder:
public static void winner() {
StringBuilder out = new StringBuilder("THE WINNER IS ");
if (position1 >= 100) {
out.append(name1);
} else if (position2 >= 100 {
out.append(name2);
} else {
return; // Preserve previous behavior just in case, remove this if it's not needed
}
System.out.println(out);
}
关于java - StringBuffer 如何与 .append 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14287884/