java - 在 java 中使用字符串格式打印列

标签 java string-formatting

我尝试用 java 打印输出结果是这样的

---------------------------------
             qty   price   code
Coffee       2     12.000    T1
Tea          1     10.000    T1
Orange Juice 1     15.000    T1
Pineapple    1     20.000    T1
Juice
Tap Water    1     9000      T1
---------------------------------

到目前为止,这是我的代码

    System.out.print("\n");
    System.out.print("--------------------------------");
    System.out.print("\n");
    System.out.print(String.format("%-12s %-5s %-7s %-4s\n","","qty","price","code"));
    System.out.print("-------------------------------\n");
    System.out.print(String.format("%-12s %-5s %-7s %4s\n","Coffee","2","12.000","T1"));
    System.out.print(String.format("%-12s %-5s %-7s %4s\n","Tea","1","10.000","T1"));
    System.out.print(String.format("%-12s %-5s %-7s %4s\n","Orange Juice","1","15.000","T1"));
    System.out.print(String.format("%-12s %-5s %-7s %4s\n","Pineapple Juice","1","20.000","T1"));
    System.out.print(String.format("%-12s %-5s %-7s %4s\n","Tap Water","1","9000","T1"));
    System.out.print("--------------------------------");
    System.out.print("\n");

代码的输出是

---------------------------------
             qty   price   code
Coffee       2     12.000    T1
Tea          1     10.000    T1
Orange Juice 1     15.000    T1
Pineapple Juice 1     20.000    T1
Tap Water    1     9000      T1
---------------------------------

有谁知道如何修改我的代码以便我可以按我想要的方式打印:)

最佳答案

System.out.print("\n");
    System.out.print("--------------------------------");
    System.out.print("\n");
    System.out.print(String.format("%-15s %-5s %-7s %-4s\n","","qty","price","code"));
    System.out.print("-------------------------------\n");
    System.out.print(String.format("%-15s %-5s %-7s %4s\n","Coffee","2","12.000","T1"));
    System.out.print(String.format("%-15s %-5s %-7s %4s\n","Tea","1","10.000","T1"));
    System.out.print(String.format("%-15s %-5s %-7s %4s\n","Orange Juice","1","15.000","T1"));
    System.out.print(String.format("%-15s %-5s %-7s %4s\n","Pineapple Juice","1","20.000","T1"));
    System.out.print(String.format("%-15s %-5s %-7s %4s\n","Tap Water","1","9000","T1"));
    System.out.print("--------------------------------");
    System.out.print("\n");

因为 Pineapple Juice 的长度比其他的多,所以留了 15s 的空格,希望对您有所帮助

关于java - 在 java 中使用字符串格式打印列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27817940/

相关文章:

java - 如何在MySQL中创建与包含关系的组合键相对应的java对象

java - 我收到一条错误消息,指出无法从 Vehicle 类型对非静态方法 GetNUmber() 进行静态引用

PHP,文本区域中的 strip_tags 剥离\n。如何阻止它?

java - Android混淆器: How to set up in Eclipse?

Java Applet 到多面板应用程序

java - 优化tomcat启动时间

php - 是否有 PHP 函数可以将货币金额格式化为会计格式?

python - string.format(...,**locals()) 的缩写形式

string - 固定宽度数字格式化python 3

python - 从python中为postgresql中的union中的每个查询选择特定列