在Java中对齐printf输出

qxgroojn  于 2022-12-25  发布在  Java
关注(0)|答案(5)|浏览(153)

我需要从一个数组中显示带有价格的项目列表,并希望对齐价格。我几乎可以工作,但需要改进。下面是代码和输出。如何使所有价格对齐的想法?到目前为止,一些工作,但一些没有。

//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
9fkzdhlc

9fkzdhlc1#

你可以试试下面的例子。一定要在宽度前使用“-”来确保左缩进。默认情况下它们将右缩进;这可能不符合你的目的。

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的回答的评论,但我仍然没有评论的权限,所以回答它。

nukf8bse

nukf8bse2#

我们想到的一个简单解决方案是使用String空间块:

String indent = "                  "; // 20 spaces.

当打印出一个字符串时,计算实际的缩进并将其添加到末尾:

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

这将把空格的数目传递给字符串,并把它们放在同一列中。

9vw9lbht

9vw9lbht3#

printf和类似printf的方法的格式规范有一个可选的width参数。

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

将宽度调整为所需值。

cunj1qz1

cunj1qz14#

下面是一个可能的解决方案,它将根据最长的bookTypes值设置bookType列的宽度(即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]);
        }
    }
}
hof1towb

hof1towb5#

你可以参考这个博客打印格式化的彩色文本上控制台
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");
}

相关问题