【问题标题】:Printing multiline string in Java [closed]在Java中打印多行字符串[关闭]
【发布时间】:2013-12-23 12:17:36
【问题描述】:

我有以下字符串

String str = " Hello There \n How are you "

我正在尝试使用 System.out.println(str);System.out.print(str); 打印它 但我得到的只是Hello There

我怎样才能全部打印出来?

【问题讨论】:

  • 应该可以。你是如何运行你的程序的?
  • @Keppil 使用 eclipse,因为我正在编写 Android 应用程序
  • 你的 IDE 没关系。你的代码是对的。
  • @Sergi 那为什么我只得到了一半的句子?
  • 工作证明:ideone.com/tDcigS

标签: java printing multiline


【解决方案1】:

避免使用\n 和其他平台相关值:

final String NEW_LINE = System.getProperty("line.separator");
String str = String.format("Hello There %s How are you", NEW_LINE);
System.out.println(str);

【讨论】:

    【解决方案2】:
        String str = " Hello There \n How are you ";
        System.out.println(str);
    

    正如您所尝试的,它工作正常。似乎是你没有很好地阅读你的输出。签出this

    【讨论】:

      【解决方案3】:

      要在 Windows 上输出换行符,您应该使用 \r\n,它将光标放在新行的开头。在 Linux 上,您应该使用 \n,它会自动完成这项工作。 System.out.println() 自动选择合适的行并在字符串末尾打印一个新行。所以你的(平台无关的)代码应该是:

      System.out.println("Hello There");
      System.out.println("How are you");
      

      【讨论】:

        猜你喜欢
        • 2011-09-11
        • 1970-01-01
        • 1970-01-01
        • 2015-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多