Java:字符串:没有给出好的结果

标签 java string query-by-example

我正在尝试这个教科书示例,我检查了一下,这正是书中的内容:-

public class StringBuilderConstructors
{
  public static void main(String[] args)
  {
    Object objectRef = "hello";
    String string = "goodbye";
    char[] charArray = {'a','b','c','d','e','f'};
    boolean booleanValue = true;
    char characterValue = 'Z';
    int integerValue = 7;
    long longValue = 10000000000L;
    float floatValue = 2.5f;
    double doubleValue = 33.333;

    StringBuilder lastBuffer = new StringBuilder("last buffer");
    StringBuilder buffer = new StringBuilder();

    buffer.append(objectRef)
    .append(System.getProperty("line.seperator"))
    .append(string)
    .append(System.getProperty("line.seperator"))
    .append(charArray)
    .append(System.getProperty("line.seperator"))
    .append(booleanValue)
    .append(System.getProperty("line.seperator"))
    .append(characterValue)
    .append(System.getProperty("line.seperator"))
    .append(integerValue)
    .append(System.getProperty("line.seperator"))
    .append(longValue)
    .append(System.getProperty("line.seperator"))
    .append(floatValue)
    .append(System.getProperty("line.seperator"))
    .append(doubleValue)
    .append(System.getProperty("line.seperator"))
    .append(lastBuffer);

    System.out.printf("buffer contains%n%s %n", buffer.toString());
  }
}

但它给我的结果是完全错误的。

缓冲区包含 hellonullgoodbyenullabcdefnulltruenullZnull7null10000000000null2.5null33.333null最后一个缓冲区

这整件事不应该排在一行中。

最佳答案

这个System.getProperty("line.seperator")不正确,你想要System.lineSeparator()喜欢

buffer.append(objectRef) //
        .append(System.lineSeparator()) //
        .append(string) //
        .append(System.lineSeparator()) //
        .append(charArray) //
        .append(System.lineSeparator()) //
        .append(booleanValue) //
        .append(System.lineSeparator()) //
        .append(characterValue) //
        .append(System.lineSeparator()) //
        .append(integerValue) //
        .append(System.lineSeparator()) //
        .append(longValue) //
        .append(System.lineSeparator()) //
        .append(floatValue) //
        .append(System.lineSeparator()) //
        .append(doubleValue) //
        .append(System.lineSeparator()) //
        .append(lastBuffer);

或者消除buffer并直接使用最终的printf(注意printf适本地翻译%n),例如

System.out.printf("buffer contains%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n%s%n", 
        objectRef, string, new String(charArray), booleanValue, 
        characterValue, integerValue, longValue, floatValue, doubleValue, 
        lastBuffer);

关于Java:字符串:没有给出好的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53551167/

相关文章:

java - 改进java字符串比较方法的运行时间和风格?

hibernate - 关联示例查询

Spring JPA ExampleMatcher比较日期条件

java - 将 XML 文档转换为 POJO

JavaFx自定义条形图鼠标事件未触发

string - 在 Fortran 中分配字符数组

java - 字符串中 1 和 0 的最大交替子序列

spring - 按示例查询 Spring 数据

java - 通过 Android 模拟器和 xampp 服务器连接到本地主机

java - 如何使用 Jsoup 从 SOAP 响应中解析 XML 元素