4

I have some code for calculating properties of a circle:

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

    }
}

It calculates circumference, but not the rest.

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
4

3 回答 3

8

r是一个int,所以r*2也是一个int,这意味着在你的第二个打印语句%f中不能使用。试试%d那里。

回想一下,这%f是针对浮点数而%d针对整数的。Formatter这在(请参阅格式字符串语法)的文档中进行了概述。

于 2013-08-30T22:47:20.287 回答
3

(r*2)将是 aint而不是 a floatas risint2is int%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.
于 2013-08-30T22:47:29.440 回答
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));
    }
}
于 2017-01-19T20:26:03.223 回答