Reputation: 61
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
Upvotes: 5
Views: 35502
Reputation: 9
This is because you had to put %d
format instead of %f
in the result of the diameter
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));
}
}
Upvotes: 1
Reputation: 41945
(r*2)
will be an int
and not a float
as r
is int
and 2
is int
. Use %d
instead
%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.
Upvotes: 3
Reputation: 129507
r
is an int
, so r*2
is also an int
, meaning that in your second print statement %f
cannot be used. Try %d
there instead.
Recall that %f
is for floating point numbers while %d
is for integers. This is outlined in the documentation of Formatter
(see Format String Syntax).
Upvotes: 9