java - StringBuffer 如何与 .append 一起使用

标签 java string-concatenation stringbuffer

我正在做一个计算机科学项目,我需要合并 StringBuffer。我需要帮助了解 .append 的作用以及连接的含义。有人告诉我,我可以通过将 .appendStringBuffer 结合使用来显示谁是(我的游戏)的赢家。

  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/

相关文章:

java - <f :event type ="preRenderView"> causes all buttons to call the same method

python - 根据开始和结束字符python在列表中追加行

java - 字符串缓冲区到字符串转换异常?

java - 从 python 脚本设置环境变量

java - 将 JAR 转换为 Swing 组件

连接两个字符数组?

java - Spring Controller 是线程安全的吗?

java - 构造对象时对对象的最终引用

c - 从c中的字符串数组中获取第一个字符串