计算公式时出现Java错误

时间:2016-09-06 07:14:05

标签: java

我正在尝试编写一个简单的程序。它符合,但在进入所需的测量后,它会爆炸。看起来它可能是转换错误,但所有数字都是浮点数。

有人可以帮忙吗?

import javax.swing.JOptionPane;
public class Test
{
    public static void main(String[] args)
    {
       String lengthString, radiusString ;

         radiusString = JOptionPane.showInputDialog(null, "Enter the radius of the cylinder. ", JOptionPane.QUESTION_MESSAGE); 
          float radius = Float.parseFloat(radiusString); 

       lengthString = JOptionPane.showInputDialog(null, "Enter the length of the cylinder. ", JOptionPane.QUESTION_MESSAGE);
        float length = Float.parseFloat(lengthString);


       float pi = 3.14f ;
       float two = 2f;
       float bottomArea = (radius * radius * pi);
       float cylinderArea = (two * radius * pi * length) + (two + bottomArea) ;
       float volume = (bottomArea * length);



        JOptionPane.showMessageDialog(null, String.format("The length of the cylinder is  %.02f \n", length +
           "The radius of the cylinder is %.02f \n", radius +
            "The area of the cylinder is %.02f \n", cylinderArea +
        "The volume of the cylinder is %.02f \n", volume));
    }

}
java.util.IllegalFormatConversionException: f != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
    at java.util.Formatter$FormatSpecifier.printFloat(Formatter.java:2806)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2753)
    at java.util.Formatter.format(Formatter.java:2520)
    at java.util.Formatter.format(Formatter.java:2455)
    at java.lang.String.format(String.java:2940)
    at Test.main(Test.java:37)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

1 个答案:

答案 0 :(得分:2)

格式String f代表浮点值,但format调用中的第一个参数是String

length + "The radius of the cylinder is %.02f \n"

你应该像这样格式化你的字符串:

String.format("The length of the cylinder is  %.02f \n" +
            "The radius of the cylinder is %.02f \n" +
            "The area of the cylinder is %.02f \n" +
            "The volume of the cylinder is %.02f \n",
            length, radius, cylinderArea, volume)