有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Ilegal格式转换问题

我可以从第二个打印输出中得到一个输出-17.83,但是当我尝试使用第一个系统输出语句时,我一直得到非法FormatConversionException

import java.util.Formatter;
public class Q1
{
    public static void main (String []args)
    {
        double r = Double.parseDouble(args[0]);
        double a = Double.parseDouble(args[1]);

        double area = 0.5*(Math.pow(r, 2))*(((a*(22/7))/180)- Math.sin((a*(22/7))/180));
        System.out.format("Area is %.2f", area + " when radius is " + r + " and angle is " + a); 
        System.out.printf("%.2f", area);

共 (2) 个答案

  1. # 1 楼答案

    您的格式字符串应该包含所有具体的字符串元素,而您的格式字符串不包含这些元素

    System.out.format("Area is %.2f", area + " when radius is " + r + " and angle is " + a);
    

    而是

    System.out.format("Area is %.2f when radius is %.2f and angle is %.2f", area, r, a);
    

    以后,在询问错误时,始终发布完整的错误消息。不要转述它,因为你可能会遗漏消息中包含的重要信息

  2. # 2 楼答案

    这个

    System.out.format("Area is %.2f", area + " when radius is " + r + " and angle is " + a); 
    

    应该是(为了编译)

    System.out.format("Area is %.2f when radius is " + r + " and angle is " + a, area);
    

    为了好看:

    System.out.format("Area is %.2f when radius is %.2f and angle is %.2f",  area, r, a);
    

    在您的版本中,您将"Area is %.2f"作为第一个参数传递,类似于"6.28244564556 when radius is 1.0 and angle is 6.28244564556"。(数字会有所不同)。第二个参数显然不能解析为浮点。因此出现了错误