我究竟做错了什么? Java IllegalFormatConversionException [英] What am I doing wrong? Java IllegalFormatConversionException

查看:137
本文介绍了我究竟做错了什么? Java IllegalFormatConversionException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


推荐答案

r int ,所以 r * 2 也是 int ,这意味着你的第二个打印语句%f 无法使用。改为尝试%d

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.

回想%f 是浮点数,而%d 是整数。 Formatter (请参阅格式字符串语法 )。

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

这篇关于我究竟做错了什么? Java IllegalFormatConversionException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆