4

When I run my program, I get this:

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)

I want to display this so that the months align with each column of numbers, like Jan aligns with the first column of numbers and so on. I know that there are 7 blank spaces between each column of number if the months are aligned. The thing is, I don't know how to create blank spaces, like blank spaces so the months won't show up on top of the Temperature: heading, with printf. Any help will be greatly appreciated.

4

4 回答 4

3

您需要使用System.out.printf()并为宽度传递适当的标志,请参阅此处了解格式化语法。

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);
于 2013-11-13T18:40:21.343 回答
-2

试试这个..你可以指定每个打印之间的空格..

        String[] day = {"Sun", "Mon", "Tues", "Friday","Saturday"};
        for(String s :day){
            System.out.printf("%15s", s);
        }
于 2013-11-13T18:44:43.107 回答
-5

这将打印四个空格加上该月占用的三个空格。此外,如果您只想打印字符串,您实际上并不需要 printf。下面是两个选项。

System.out.printf("    %s", month);

或者

System.out.print("    " + month);

我还建议想出一种方法来做到这一点,而无需对空格进行硬编码。也许设置一个循环来打印可以改变宽度的空间。

于 2013-11-13T18:43:24.853 回答
-5

试试这个 System.out.println("\n");

于 2016-07-29T04:42:48.937 回答