5

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.

user2967353
  • 257
  • 3
  • 9
  • 18

4 Answers4

3

You need to use System.out.printf() and passing the appropriate flags for the width, see here for the syntax for formatting.

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);
A4L
  • 17,353
  • 6
  • 49
  • 70
-2

try this.. you can specify spaces between each print..

        String[] day = {"Sun", "Mon", "Tues", "Friday","Saturday"};
        for(String s :day){
            System.out.printf("%15s", s);
        }
subash
  • 3,116
  • 3
  • 18
  • 22
-5

This will print exactly four spaces plus the three taken up by the month. Also, if you just want to print Strings you don't really need printf. Below are two options.

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

or

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

I would also recommend coming up with a way to do this without hard coding the spaces. Maybe set up a loop to print spaces which can change the width.

johnsoe
  • 664
  • 1
  • 5
  • 13
-5

try this System.out.println("\n");