What am I doing wrong? Java IllegalFormatConversionException

后端 未结 3 450
不思量自难忘°
不思量自难忘° 2021-01-13 17:50

I have some code for calculating properties of a circle:

package circleinfo;

import java.util.Scanner;

public class Circleinfo {

    public static void ma         


        
相关标签:
3条回答
  • 2021-01-13 18:24

    (r*2) will be an int and not a float as r is int and 2 is int. Use %d instead

    %c          char    Character
    %d          int         Signed decimal integer.  
    %e, %E      float       Real number, scientific notation (lowercase or uppercase exponent marker)
    %f         float    Real number, standard notation.
    
    0 讨论(0)
  • 2021-01-13 18:27

    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.

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

    0 讨论(0)
  • 2021-01-13 18:42

    This is because you had to put %d format instead of %f in the result of the diameter

    import java.util.Scanner;
    public class CircleInfo{
        public static void main(String[] args){
    
                Scanner input = new Scanner(System.in);
                int radio;
                System.out.print("Input radio: ");
                radio = input.nextInt();
    
                System.out.printf("%s%d%n","Diameter= ",(2*radio));
                System.out.printf("%s%f%n","Area= ",(Math.PI*radio*radio));
                System.out.printf("%s%f%n","Circumference = ",(2*Math.PI*radio));
        }
    }
    
    0 讨论(0)
提交回复
热议问题