gpt4 book ai didi

java - 无法将字符串格式化为 Java 中的预期输出

转载 作者:行者123 更新时间:2023-12-02 15:18:29 25 4
gpt4 key购买 nike

我想将输出格式化为如下所示

  Account                      Date        Hours  Skill
--------------------------- ---------- ----- --------------------
Acme Industries 03/06/2006 8 Software Engineer

但我明白了:

Account                     Date       Hours   Skill
--------------------------- ---------- ----- --------------------
Acme Industries 08/18/14 8 software Engineer

我的代码如下:

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class TestingStuff {

public static void main(String[] args){
Calendar calendar = Calendar.getInstance();
calendar = new GregorianCalendar(2014, 07, 18);
Date startDate = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy");
String formatted = simpleDateFormat.format(startDate);
String separator = "--------------------------- ---------- ----- --------------------\n";
String result="";
String header=String.format("%-27s %-10s %-7s %s%n", "Account","Date","Hours","Skill");

String output=String.format("%-27s %-10s %-7s %s%n", "Acme Industries",
formatted,8,"Software Engineer");

System.out.println(header+separator+output);
}

}

我需要一些关于如何解决此类格式问题的提示,例如左右填充...

最佳答案

我会使用这样的东西

// get i dashes as a string.
private static String getDashes(int i) {
StringBuilder sb = new StringBuilder();
while (i > 0) {
sb.append("-");
--i;
}
return sb.toString();
}

public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar = new GregorianCalendar(2014, 07, 18);
Date startDate = calendar.getTime();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy");
String formatted = simpleDateFormat.format(startDate);

// one format string
String fmtString = "%-27s %-10s %5s %s%n";
// get the various dashes.
String separator = String.format(fmtString, getDashes(26),
getDashes(9), getDashes(5), getDashes(20));
// format the header
String header = String.format(fmtString, "Account", "Date", "Hours",
"Skill");

// format the body
String output = String.format(fmtString, "Acme Industries", formatted,
8, "software Engineer");

// print
System.out.println(header + separator + output);
}

哪些输出

Account                      Date        Hours  Skill
-------------------------- --------- ----- --------------------
Acme Industries 08/18/14 8 software Engineer

关于java - 无法将字符串格式化为 Java 中的预期输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21269814/

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