gpt4 book ai didi

java - 对齐和缩进数组元素 - Java

转载 作者:行者123 更新时间:2023-12-01 16:42:27 25 4
gpt4 key购买 nike

我想将 double 数组元素与相关 String 数组元素的右侧对齐。

示例输出:

TITLE         TICKET TYPE        COST
-------------------------------------
Tulip Garden Entry $10.0
Tour + Ride $20.0
-------------------------------------
Museum Entry $0.0
Guided Tour $5.0
-------------------------------------
...

以下是我到目前为止所做的事情。

EventData.java

private String[] ticketTypeTitle;
private double[] ticketTypeCost;

...

public String[] getTicketTitles() { return this.ticketTypeTitle; }
public double[] getTicketCosts() { return this.ticketTypeCost; }

Main.java

String pattern = "%-28s %-28s %-1s";

System.out.printf(pattern, "TITLE", "TICKET TYPE", "COST");
System.out.println("-----------------------------------------------);

for (int i = 0; i < eventCount; i++ {
System.out.format(pattern, eventData[i].getTitle(), String.join("\n\t\t\t\t\t\t", eventData[i].getTicketTitles(), "$" + String.join("\n\t\t\t\t\t\t", Arrays.toString(eventData[i].getTicketCosts().replaceAll("\\[|\\]|\\,", "")));
System.out.println("---------------------------------------------");
}

问题#1:for循环的第一行,我无法让美元符号显示在每个数组元素之前(对于票证)仅成本)。

问题#2:我希望成本值也与票据类型一致,类似于上面的输出示例,但我还没有弄清楚如何做到这一点。

感谢您的帮助!

最佳答案

您需要对数字使用单独的格式化程序,以确保它们的格式正确。我还将 $ 符号直接添加到格式化程序模式中。见下文。

以下是适合您的示例代码:

String[] titleArray = {"title1", "title2", "title3", "title4", "title5"};
String[] typeArray = {"type1", "type2", "type3", "type4", "type5"};
double[] costArray = { 10.0, 20.0, 0.0, 5.0, 3.33 };

String pattern = "%-28s %-28s $%5.2f";
String patternHeader = "%-28s %-28s %-1s";

System.out.printf(patternHeader, "TITLE", "TICKET TYPE", "COST");
System.out.println();
System.out.println("-----------------------------------------------");

for (int i = 0; i < 5; i++) {
System.out.format(pattern, titleArray[i], typeArray[i], costArray[i]);
System.out.println();
}
System.out.println("---------------------------------------------");

关于java - 对齐和缩进数组元素 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61837181/

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