gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 05:12:41 25 4
gpt4 key购买 nike

我尝试用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com