在 Java 中对齐 printf 输出 [英] Align printf output in Java

查看:33
本文介绍了在 Java 中对齐 printf 输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从数组中显示带有价格的项目列表,并希望调整价格.我几乎可以正常工作,但需要改进.下面是代码和输出.任何想法如何使所有价格保持一致?到目前为止,有些工作但有些没有.提前致谢.

I need to display a list of items with their prices from an array and would like to align the prices. I almost have it working but needs improvements. Below is the code and the output. Any ideas how to make all prices aligned? So far some work but some don't. Thanks in advance.

//for loop
System.out.printf("%d. %s 		 $%.2f
",
                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

推荐答案

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

You can try the below example. Do use '-' before the width to ensure left indentation. By default they will be right indented; which may not suit your purpose.

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 答案的评论,但我仍然无权发表评论,因此无法回答.

PS: This could go as a comment to DwB's answer, but i still don't have permissions to comment and so answering it.

这篇关于在 Java 中对齐 printf 输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆