【问题标题】:Align printf output in Java在 Java 中对齐 printf 输出
【发布时间】:2013-04-04 09:02:51
【问题描述】:

我需要显示一个包含数组价格的商品列表,并希望调整价格。我几乎让它工作,但需要改进。下面是代码和输出。任何想法如何使所有价格一致?到目前为止,有些工作,但有些没有。提前致谢。

//for loop
System.out.printf("%d. %s \t\t $%.2f\n",
                i + 1, BOOK_TYPE[i], COST[i]);

输出:

1. Newspaper         $1.00
2. Paper Back        $7.50
3. Hardcover book        $10.00
4. Electronic book       $2.00
5. Magazine          $3.00

【问题讨论】:

标签: java alignment printf text-align


【解决方案1】:

你可以试试下面的例子。请在宽度前使用“-”以确保左缩进。默认情况下,它们将正确缩进;这可能不适合您的目的。

System.out.printf("%2d. %-20s $%.2f%n",  i + 1, BOOK_TYPE[i], COST[i]);

格式化字符串语法:http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

格式化数字打印输出:https://docs.oracle.com/javase/tutorial/java/data/numberformat.html

PS:这可以作为对 DwB 答案的评论,但我仍然没有评论的权限,所以回答它。

【讨论】:

    【解决方案2】:

    想到一个简单的解决方案是有一个String 空格块:

    String indent = "                  "; // 20 spaces.
    

    打印字符串时,计算实际缩进并添加到末尾:

    String output = "Newspaper";
    output += indent.substring(0, indent.length - output.length);
    

    这将调解字符串的空格数,并将它们全部放在同一列中。

    【讨论】:

    • 看到这样的答案让我希望 Java 的 StringpadLeftpadRight 等,就像其他编程语言的标准库一样...
    • Java 确实有 StringUtils.leftPad() 和 StringUtils.rightPad()。这些是 Apache Commons Lang 的一部分。
    【解决方案3】:

    printf 和类似 printf 的方法的格式规范采用可选的宽度参数。

    System.out.printf( "%10d. %25s $%25.2f\n",
                       i + 1, BOOK_TYPE[i], COST[i] );
    

    将宽度调整为所需值。

    【讨论】:

    • 首先,不要在对某人一无所知的情况下称其为懒惰。其次,我是一名 Java 初学者,但我确实读过 printf 并且我知道 %10d 将在变量前打印 10 个空格。现在,万事通先生,不懒惰,您的代码远不及我所需要的。如果您阅读我的问题,我需要左对齐,除了第二个变量之后的空格需要更改(不是常量),因此第三个变量也对齐。不管怎么说,多谢拉。美好的一天。
    • 如果您阅读过 printf 文档,那么您会知道 %10d 指定了 10 的字段宽度,而 %010d 指定了宽度为 10 的零左填充字段。考虑阅读文档。
    • 阅读文档会告诉您 - 作为标志将左对齐该字段。 ex %-10d
    【解决方案4】:

    这是一个潜在的解决方案,它将设置 bookType 列的宽度(即 bookTypes 值的格式) 基于最长的 bookTypes 值。

    public class Test {
        public static void main(String[] args) {
            String[] bookTypes = { "Newspaper", "Paper Back", "Hardcover book", "Electronic book", "Magazine" };
            double[] costs = { 1.0, 7.5, 10.0, 2.0, 3.0 };
    
            // Find length of longest bookTypes value.
            int maxLengthItem = 0;
            boolean firstValue = true;
            for (String bookType : bookTypes) {
                maxLengthItem = (firstValue) ? bookType.length() : Math.max(maxLengthItem, bookType.length());
                firstValue = false;
            }
    
            // Display rows of data
            for (int i = 0; i < bookTypes.length; i++) {
                // Use %6.2 instead of %.2 so that decimals line up, assuming max
                // book cost of $999.99. Change 6 to a different number if max cost
                // is different
                String format = "%d. %-" + Integer.toString(maxLengthItem) + "s \t\t $%9.2f\n";
                System.out.printf(format, i + 1, bookTypes[i], costs[i]);
            }
        }
    }
    

    【讨论】:

      【解决方案5】:

      您可以参考此博客在控制台上打印格式化的彩色文本

      https://javaforqa.wordpress.com/java-print-coloured-table-on-console/

      public class ColourConsoleDemo {
      /**
      *
      * @param args
      *
      * "\033[0m BLACK" will colour the whole line
      *
      * "\033[37m WHITE\033[0m" will colour only WHITE.
      * For colour while Opening --> "\033[37m" and closing --> "\033[0m"
      *
      *
      */
      public static void main(String[] args) {
      // TODO code application logic here
      System.out.println("\033[0m BLACK");
      System.out.println("\033[31m RED");
      System.out.println("\033[32m GREEN");
      System.out.println("\033[33m YELLOW");
      System.out.println("\033[34m BLUE");
      System.out.println("\033[35m MAGENTA");
      System.out.println("\033[36m CYAN");
      System.out.println("\033[37m WHITE\033[0m");
      
      //printing the results
      String leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
      
      System.out.format("|---------Test Cases with Steps Summary -------------|%n");
      System.out.format("+----------------------+---------+---------+---------+%n");
      System.out.format("| Test Cases           |Passed   |Failed   |Skipped  |%n");
      System.out.format("+----------------------+---------+---------+---------+%n");
      
      String formattedMessage = "TEST_01".trim();
      
      leftAlignFormat = "| %-20s | %-7d | %-7d | %-7d |%n";
      System.out.print("\033[31m"); // Open print red
      System.out.printf(leftAlignFormat, formattedMessage, 2, 1, 0);
      System.out.print("\033[0m"); // Close print red
      System.out.format("+----------------------+---------+---------+---------+%n");
      }
      

      【讨论】:

      • 博客已经消失,但您的格式化字符串示例仍然有用。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-12
      相关资源
      最近更新 更多