我正在尝试使用Java格式化一行数据,以便每列都排列。我目前正在使用标签,但它似乎没有用。
这就是我的尝试:
System.out.printf("Town\tDate\tWind Speed\tDirection\tTemp(F)\tTemp(C)\tWind Chill(C)\tReporter\n");
System.out.printf(town + "\t" + date + "\t" + windSpeed + "\t" + direction + "\t" +
getFahrenheit(tempC) + "\t" + tempC + "\t" + getWindChillFactor(windSpeed, tempC) + "\t" +
reporterCode + "\n");
更新
答案 0 :(得分:0)
您正在使用的printf
方法接受格式字符串作为第一个参数,并根据格式解释参数。在您的情况下,您需要一个字符串的最小空格数。这可以使用正确的格式字符串来实现,例如:
System.out.println("%20s", town);
这会将town打印为字符串,最小宽度为20个字符。有正确对齐,舍入浮点等的规则。有关详细信息,请参阅Formatter。
答案 1 :(得分:0)
在Java 8中尝试使用它应该可以工作:
public class test {
public static void main(String args[]) {
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","Town","Date","Wind Speed","Direction","Temp(F)","Temp(C)","Wind Chill","Reporter");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","Portland","12/10/15","2.50","W","36.50","2.50","1.56","PS");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","orango","12/10/15","2.50","NW","36.50","2.50","1.56","PS");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","calais","12/10/15","2.50","W","36.50","2.50","1.56","PS");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","calais","12/10/15","2.50","W","36.50","2.50","1.56","PS");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","Portland","12/10/15","2.50","W","36.50","2.50","1.56","PS");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","Portland","12/10/15","2.50","W","36.50","2.50","1.56","PS");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","bangor","12/15/15","2.50","W","36.50","2.50","1.56","PS");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","orango","12/19/15","2.50","NW","36.50","2.50","1.56","PS");
}
}
修复更新图片:
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","Orono","12/15/15","2.50","W","36.50","2.50","1.56","OT");
System.out.printf("%-12s %-12s%-12s%-12s%-12s%-12s%-12s%s\n","Orono","12/19/15","3.10","NW","36.72","2.90","0.42","SS");
尝试以上代码: