Java中用double和int实现带返回值的圆周长/面积计算异常问题
解决IllegalFormatConversionException异常及圆计算方法实现
异常根因
java.util.IllegalFormatConversionException 说白了就是你用格式化输出(比如printf)时,占位符的类型和你传入的变量类型不匹配。比如用%d(整数占位符)去输出double类型的周长,或者反过来用%f输出整数类型的像素值,都会触发这个异常。
符合需求的完整代码
下面是满足你要求的代码,同时规避了格式化类型不匹配的问题:
public class CircleCalculator { // 用Java自带的Math.PI比自己写3.14精确得多 private static final double PI = Math.PI; // 处理毫米级(double)半径的计算 public static double[] calculateMmCircle(double radius) { double circumference = 0; double area = 0; if (radius >= 0) { circumference = 2 * PI * radius; area = PI * radius * radius; } return new double[]{circumference, area}; } // 处理像素级(int)半径的计算,结果转long保证整数单位 public static long[] calculatePxCircle(int radius) { long circumference = 0; long area = 0; if (radius >= 0) { circumference = Math.round(2 * PI * radius); area = Math.round(PI * radius * radius); } return new long[]{circumference, area}; } public static void main(String[] args) { // 测试正常毫米半径 double mmRadius = 5.5; double[] mmResults = calculateMmCircle(mmRadius); // double类型对应%f占位符,避免类型不匹配 System.out.printf("毫米半径%.2f:周长=%.2fmm,面积=%.2fmm²%n", mmRadius, mmResults[0], mmResults[1]); // 测试负数毫米半径 double negativeMm = -3.2; double[] negativeMmResults = calculateMmCircle(negativeMm); System.out.printf("负数毫米半径%.2f:周长=%.2fmm,面积=%.2fmm²%n", negativeMm, negativeMmResults[0], negativeMmResults[1]); // 测试正常像素半径 int pxRadius = 10; long[] pxResults = calculatePxCircle(pxRadius); // int/long类型对应%d占位符 System.out.printf("像素半径%d:周长=%dpx,面积=%dpx²%n", pxRadius, pxResults[0], pxResults[1]); // 测试负数像素半径 int negativePx = -5; long[] negativePxResults = calculatePxCircle(negativePx); System.out.printf("负数像素半径%d:周长=%dpx,面积=%dpx²%n", negativePx, negativePxResults[0], negativePxResults[1]); } }
关键注意事项
- 常量PI:优先用
Math.PI,精度更高,不用自己手动定义近似值 - 格式化匹配:
- 输出
double类型必须用%f(可以加.2保留两位小数) - 输出
int/long类型必须用%d
- 输出
- 负数处理:判断半径小于0时,直接返回0值,符合需求
- 单位一致性:毫米计算保留
double保证精度,像素计算后转long,因为像素是整数单位
你可能踩的坑(触发异常的错误代码)
比如你之前可能写了类似下面的代码,直接导致类型不匹配:
// 错误:用%d格式化double类型的area System.out.printf("面积是%d", area); // 错误:用%f格式化int类型的周长,虽然偶尔能运行,但严格来说会触发异常 System.out.printf("像素周长是%f", pxCircumference);
只要把占位符和变量类型对应上,这个异常就解决了。
内容的提问来源于stack exchange,提问作者z2214562712
相关产品推荐
相关产品推荐

