我的程序应该打印出这样的表格:

  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


它甚至可以编译,但是当我运行它时,我得到一个错误。我不知道该如何解决。这是我所拥有的:

public class FractionOfDay {
    static double frac = 0;
    static double timeSecs = 0;
    static int time = 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.printf("%8.4f", frac);

     }

        else if (half == 'A') {
          timeSecs = ((hour * 3600) + (minute * 60) + second);
          frac = (timeSecs / 86400);
          System.out.printf("%8.4f", frac);

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

    }

}

public static void main (String [] args) {
    int h = 12;
    double f12 = 0.0000;
    System.out.println("        Time     Fraction Since Midnight");
    System.out.printf("%8d:00 AM\n", h);
    for (int i = 1; i <= 11; i++) {
     System.out.printf("%8d:00 AM\n", i);
    }
    System.out.printf("%8d:00 PM\n", h);
    for (int i = 1; i <= 11; i++) {
     System.out.printf("%8d:00 PM\n", i);
    }

    System.out.printf("%8d:00 PM\n", f12);

     for (int i = 1; i <= 11; i++) {
     fractionOfDay(i, 0, 0, 'A');
    }

    for (int i = 1; i <= 11; i++) {
     fractionOfDay(i, 0, 0, 'P');
    }

}

}

最佳答案

在您的main方法中,您声明了double f12 = 0.0000;,然后调用System.out.printf("%8d:00 PM\n", f12);会导致异常。

为了解决它,您可以将类型从double更改为int,因为%d中的System.out.printf("%8d:00 PM\n", f12);表示int

10-06 00:56