原文: https://beginnersbook.com/2014/01/java-program-to-calculate-area-and-circumference-of-circle/

    在本教程中,我们将看到如何在 Java 中计算圆的面积和周长。有两种方法可以做到这一点:

    1)用户交互:程序将提示用户输入圆的半径

    2)没有用户交互:半径值将在程序本身中指定。

    计划 1:

    1. /**
    2. * @author: BeginnersBook.com
    3. * @description: Program to calculate area and circumference of circle
    4. * with user interaction. User will be prompt to enter the radius and
    5. * the result will be calculated based on the provided radius value.
    6. */
    7. import java.util.Scanner;
    8. class CircleDemo
    9. {
    10. static Scanner sc = new Scanner(System.in);
    11. public static void main(String args[])
    12. {
    13. System.out.print("Enter the radius: ");
    14. /*We are storing the entered radius in double
    15. * because a user can enter radius in decimals
    16. */
    17. double radius = sc.nextDouble();
    18. //Area = PI*radius*radius
    19. double area = Math.PI * (radius * radius);
    20. System.out.println("The area of circle is: " + area);
    21. //Circumference = 2*PI*radius
    22. double circumference= Math.PI * 2*radius;
    23. System.out.println( "The circumference of the circle is:"+circumference) ;
    24. }
    25. }

    输出:

    Enter the radius: 1
    The area of circle is: 3.141592653589793
    The circumference of the circle is:6.283185307179586
    

    程序 2:

    /**
     * @author: BeginnersBook.com
     * @description: Program to calculate area and circumference of circle
     * without user interaction. You need to specify the radius value in 
     * program itself.
     */
    class CircleDemo2
    {
       public static void main(String args[])
       {
          int radius = 3;
          double area = Math.PI * (radius * radius);
          System.out.println("The area of circle is: " + area);
          double circumference= Math.PI * 2*radius;
          System.out.println( "The circumference of the circle is:"+circumference) ;
       }
    }
    

    输出:

    The area of circle is: 28.274333882308138
    The circumference of the circle is:18.84955592153876