我究竟做错了什么?Java IllegalFormatConversionException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18542515/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What am I doing wrong? Java IllegalFormatConversionException
提问by user2734475
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
采纳答案by arshajii
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.
r
是int
,所以r*2
也是int
,这意味着在您的第二个打印语句%f
中不能使用。去%d
那里试试。
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).
回答by Narendra Pathai
(r*2)
will be an int
and not a float
as r
is int
and 2
is int
. Use %d
instead
(r*2)
will be anint
和 not a float
as r
isint
和2
is 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.
回答by Victor Fernández
This is because you had to put %d
format instead of %f
in the result of the diameter
这是因为你必须把%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));
}
}