无法理解IllegalArgumentException的原因

时间:2016-05-30 09:37:12

标签: java illegalargumentexception decimalformat

以下是我的代码,

// Testing class circle 
import java.text.DecimalFormat  ;
import javax.swing.JOptionPane  ;

public class CircleTest {

    public static void main( String args[] )
    {
        // instantiate Circle object
        Circle circle = new Circle( ) ;

        Point3 point = new Point3( 40, 50 ) ;

        // get circle's initial x - y coordinate and radius 
        String output = "\nX coordinate is " + circle.getX( ) +
                        "\nY coordinate is " + circle.getY( ) +
                        "\nRadius is "  + circle.getRadius() ;

        circle.setX( 35 );          // set new x - coordinate
        circle.setY( 20 );          // set new y - coordinate
        circle.setRadius( 4.25 );   // set new radius

        // get String representation of new circle value
        output += "\n\nThe new location and radius of circle are\n" + 
                   circle.toString() ;



        // format floating - point values with 2 digits of precision
        DecimalFormat twoDigits  = new DecimalFormat ( " 0.00 ") ;

        // get Circle's diameter, Circumference and area respectively
        output  += "\nDiameter is " + twoDigits.format( circle.getDiameter() ) +
                "\nCircumference is " + twoDigits.format( circle.getCircumference() ) +
                "\nArea is " + twoDigits.format( circle.getArea( ) +
                        " Test sum is: " + twoDigits.format(  point.sum( ) ) ) ;



        JOptionPane.showMessageDialog( null, output ) ;

        System.exit( 0 );
    }   // end method main

}   // end class CircleTest

我收到错误

Exception in thread "main" java.lang.IllegalArgumentException: Cannot format       given Object as a Number

    at java.text.DecimalFormat.format(DecimalFormat.java:507)

    at java.text.Format.format(Format.java:157)

    at CircleTest.main(CircleTest.java:35)

但是,如果我使用

分别附加输出,则不会出现上述错误
output += " Test sum is: " + twoDigits.format( point.sum() ) ;

为什么会这样?有什么问题?

2 个答案:

答案 0 :(得分:1)

您正在整个字符串消息中应用<html> <body> <a href='products.html#Building'>Building</a> <a href='products.html#Infrastructure'>Infrastructure</a> </body> </html> products.html <div id='Building'> <div class="container"> building<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br> </div> <div> <div id='Infrastructure'> <div class="container"> Infrastructure </div> <div> ,而不仅仅是区域:缺少format

答案 1 :(得分:0)

你被错误地放在了支架上。

这是固定的

output  += "\nDiameter is " + twoDigits.format(circle.getDiameter()) +
           "\nCircumference is " + twoDigits.format(circle.getCircumference()) +
           "\nArea is " + twoDigits.format(circle.getArea()) +
           " Test sum is: " + twoDigits.format(point.sum())  ;