【问题标题】:I can't figure out how to indent using printf我不知道如何使用 printf 缩进
【发布时间】:2020-01-31 03:16:49
【问题描述】:

我目前正在学习 Java,但遇到一些代码问题

我试着弄乱它的语法,但我不知道。

class Main {
  public static void main(String[] args) {
    System.out.printf("%14s%n", "Location: Key West, Florida");
  }
}

我想让它缩进,但什么也没发生

【问题讨论】:

标签: java


【解决方案1】:

您可以使用\t 字符将制表符空格字符添加到打印的字符串中。例如

 System.out.printf("\t%s", "public class Test {\n \t\tSystem.our.println(\"it works fine\");\n \t}");

输出:

public class Test {
    System.our.println("it works fine");
}

【讨论】:

  • 添加一堆\ts 可能不是解决手头问题的理想方法
【解决方案2】:

这是因为%14s 分配了一个 14 个字符的空格,而您的字符串比这长,所以它似乎没有效果。
想看效果试试看

System.out.printf("%34s%n", "Location: Key West, Florida");

它将给出一个 34 个字符的空格和 Right - Indent 你的字符串。
如果您想要Left - Indent,请在格式大小前添加-

System.out.printf("%-34s%n", "Location: Key West, Florida");

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2016-12-13
    • 2022-11-11
    • 2017-05-21
    • 2013-04-07
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多