程序进行编译,但随后在线程“主”中给出错误Exception java.util.IllegalFormatConversionException:d!= java.lang.Double?

时间:2018-07-16 05:22:36

标签: java printf printf-debugging

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

  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');
    }

}

}

4 个答案:

答案 0 :(得分:2)

在您的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

答案 1 :(得分:1)

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

%d用于十进制。但是您的论点是double类型的。 请看看formatting

将%d更改为%s以解决此问题-> System.out.printf("%8s:00 PM\n", f12);

答案 2 :(得分:1)

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

f12是双精度数,因此它可以表示非整数小时数。从逻辑上讲,这意味着什么?您可能不想打印

3.141592:00 PM

f12的类型更改为int

答案 3 :(得分:0)

您可以为此修改代码-

System.out.printf("%.4f:00\n", f12);

也将f12声明如下-

float f12 = 0.0000f;