En este tutorial veremos cómo calcular el área y la circunferencia del círculo en Java. Hay dos maneras de hacer esto:
1) Con la interacción del usuario: el programa le pedirá al usuario que ingrese el radio del círculo.
2) Sin interacción del usuario: el valor del radio se especificaría en el propio programa.
Programa 1:
/** * @author: BeginnersBook.com * @description: Program to calculate area and circumference of circle * with user interaction. User will be prompt to enter the radius and * the result will be calculated based on the provided radius value. */ import java.util.Scanner; class CircleDemo { static Scanner sc = new Scanner(System.in); public static void main(String args[]) { System.out.print("Enter the radius: "); /*We are storing the entered radius in double * because a user can enter radius in decimals */ double radius = sc.nextDouble(); //Area = PI*radius*radius double area = Math.PI * (radius * radius); System.out.println("The area of circle is: " + area); //Circumference = 2*PI*radius double circumference= Math.PI * 2*radius; System.out.println( "The circumference of the circle is:"+circumference) ; } }
Producción:
Enter the radius: 1 The area of circle is: 3.141592653589793 The circumference of the circle is:6.283185307179586
Programa 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) ; } }
Producción:
The area of circle is: 28.274333882308138 The circumference of the circle is:18.84955592153876