当我运行我的程序时,我明白了:
run:
Heat Index: Key West, Florida
Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
____________________________________________________________________________________________________________________________________
Temperature: 70.3 70.8 73.8 77.0 80.7 83.4 84.5 84.4 83.4 80.2 76.3 72.0
Humidity: 69.0 67.0 66.0 64.0 66.0 69.0 67.0 67.0 70.0 69.0 69.0 70.0BUILD SUCCESSFUL (total time: 0 seconds)
我想显示这个,以便月份与每列数字对齐,例如Jan与第一列数字对齐,依此类推。我知道如果月份对齐,每列数字之间有7个空格。问题是,我不知道如何创建空格,比如空格,所以这些月份不会出现在温度:标题之上,带有printf。任何帮助将不胜感激。
答案 0 :(得分:3)
您需要使用System.out.printf()并为宽度传递适当的标记,有关格式化的语法,请参阅here。
String[] months =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug",
"Sep", "Oct", "Nov", "Dec"};
Double[] temper =
{70.3, 70.8, 73.8, 77.0, 80.7, 83.4, 84.5, 84.4, 83.4, 80.2, 76.3, 72.0};
Double[] humid =
{69.0, 67.0, 66.0, 64.0, 66.0, 69.0, 67.0, 67.0, 70.0, 69.0, 69.0, 70.0};
System.out.printf(" %7s%7s%7s%7s%7s%7s%7s%7s%7s%7s%7s%7s\n",
(Object[])months);
System.out.printf("________________________________________"
+ "________________________________________________________\n");
System.out.printf("Temperature:%7.1f%7.1f%7.1f%7.1f%7.1f"
+ "%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f\n",
(Object[])temper);
System.out.printf(" Humidity:%7.1f%7.1f%7.1f%7.1f%7.1f"
+ "%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f%7.1f\n",
(Object[])humid);
答案 1 :(得分:-2)
试试这个..你可以在每个印刷品之间指定空格..
String[] day = {"Sun", "Mon", "Tues", "Friday","Saturday"};
for(String s :day){
System.out.printf("%15s", s);
}
答案 2 :(得分:-4)
这将打印四个空格加上本月占用的三个空格。此外,如果你只想打印字符串,你真的不需要printf。以下是两个选项。
System.out.printf(" %s", month);
或
System.out.print(" " + month);
我还建议在不对空间进行硬编码的情况下提出一种方法。也许设置一个循环来打印可以改变宽度的空间。
答案 3 :(得分:-4)
试试这个 的System.out.println(" \ n&#34);