我究竟做错了什么? Java IllegalFormatConversionException

时间:2013-08-30 22:45:23

标签: java

我有一些用于计算圆的属性的代码:

package circleinfo;

import java.util.Scanner;

public class Circleinfo {

    public static void main(String[] args) {

        Scanner input=new Scanner(System.in);
        int r;

        System.out.print("Enter the radius of the circle to find circumference, diameter, and area\n");

        r = input.nextInt();

        System.out.printf("The circumference is %f\n",(2*r*Math.PI));
        System.out.printf("The diameter is %f\n",(r*2));
        System.out.printf("The area is %f\n",(r*r*Math.PI));

    }
}

计算周长,但不计算其余部分。

Enter the radius of the circle to find circumference, diameter, and area

10

The circumference is 62.831853

Exception in thread "main" java.util.IllegalFormatConversionException: f != java.lang.Integer
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045)
    at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2761)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2708)
    at java.util.Formatter.format(Formatter.java:2488)
    at java.io.PrintStream.format(PrintStream.java:970)
    at java.io.PrintStream.printf(PrintStream.java:871)
    at circleinfo.Circleinfo.main(Circleinfo.java:30)
The diameter is Java Result: 1

3 个答案:

答案 0 :(得分:7)

rint,因此r*2也是int,这意味着您的第二个打印语句%f无法使用。请改为%d

回想一下,%f用于浮点数,而%d用于整数。这在Formatter的文档中有所概述(参见Format String Syntax)。

答案 1 :(得分:3)

(r*2)将是int,而不是float,因为rint2int。请改用%d

%c          char    Character
%d          int         Signed decimal integer.  
%e, %E      float       Real number, scientific notation (lowercase or uppercase exponent marker)
%f         float    Real number, standard notation.

答案 2 :(得分:1)

这是因为你必须在直径的结果中放置%d格式而不是%f

import java.util.Scanner;
public class CircleInfo{
    public static void main(String[] args){

            Scanner input = new Scanner(System.in);
            int radio;
            System.out.print("Input radio: ");
            radio = input.nextInt();

            System.out.printf("%s%d%n","Diameter= ",(2*radio));
            System.out.printf("%s%f%n","Area= ",(Math.PI*radio*radio));
            System.out.printf("%s%f%n","Circumference = ",(2*Math.PI*radio));
    }
}