-1

I've created a method that takes a time parameter, converts it into seconds, and prints its "fraction" by dividing it by the number of seconds in a day. I need to use printf to make it into a table, but I don't know how to take the fraction the method gives me and put it into a table. When I'm done, the program should print this:

table

Here is the code I've got so far:

public class FractionOfDay {

static double frac = 0; static double timeSecs = 0;

public static void fractionOfDay( int hour, int minute, int second, char half) {

    if (hour == 12 && minute == 0 && second == 0 && half == 'A') {
  frac = 0.0000;
  System.out.print(frac);

}

    else if (half == 'A') {
      timeSecs = ((hour * 360) + (minute * 60) + second);
      frac = (timeSecs / 86400);
      System.out.print(frac);

}
else if (half == 'P') {
 timeSecs = ((hour * 3600) + (minute * 60) + second + (12 * 3600));
 frac = (timeSecs / 86400);
System.out.print(frac);

}

}

public static void main (String [] args) {
    fractionOfDay(12, 0, 0, 'A');
}

}

newcode
  • 63
  • 5

1 Answers1

0

This will do it:

public static void fractionOfDay( int hour, int minute, int second, char half) {
    int timeSecs = (half == 'P' ? 43200 : 0) + (hour % 12) * 3600 + minute * 60 + second;
    System.out.printf("%7d:%02d %sM       %.4f%n", hour, minute, half, timeSecs / 86400.0);
}

Notice that the timeSecs formula has been fixed to account for hour 12 and to not use incorrect 360 multiplier.

Test

System.out.println("      Time          Fraction Since Midnight");
for (int i = 0; i < 24; i++)
    fractionOfDay((i + 11) % 12 + 1, 0, 0, (i < 12 ? 'A' : 'P'));

First call is fractionOfDay(12, 0, 0, 'A') and last call is fractionOfDay(11, 0, 0, 'P')

Output

      Time          Fraction Since Midnight
     12:00 AM       0.0000
      1:00 AM       0.0417
      2:00 AM       0.0833
      3:00 AM       0.1250
      4:00 AM       0.1667
      5:00 AM       0.2083
      6:00 AM       0.2500
      7:00 AM       0.2917
      8:00 AM       0.3333
      9:00 AM       0.3750
     10:00 AM       0.4167
     11:00 AM       0.4583
     12:00 PM       0.5000
      1:00 PM       0.5417
      2:00 PM       0.5833
      3:00 PM       0.6250
      4:00 PM       0.6667
      5:00 PM       0.7083
      6:00 PM       0.7500
      7:00 PM       0.7917
      8:00 PM       0.8333
      9:00 PM       0.8750
     10:00 PM       0.9167
     11:00 PM       0.9583
Andreas
  • 138,167
  • 8
  • 112
  • 195