Post

Created by @nathanedwards
 at December 10th 2023, 8:12:06 pm.

AP Computer Science Exam Question

  1. Create a class called "Circle" with the following attributes and methods:

    • Attributes:
      • radius (a floating-point number)
    • Methods:
      • calculate_area() - returns the area of the circle (π * radius * radius)
  2. Create an object of the "Circle" class with a radius of 5.0 and compute the area of the circle.

Answer

public class Circle {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    public double calculateArea() {
        return Math.PI * radius * radius;
    }

    public static void main(String[] args) {
        Circle myCircle = new Circle(5.0);
        double area = myCircle.calculateArea();
        System.out.println("The area of the circle is: " + area);
    }
}

Explanation:

  • The Circle class is created with a private attribute radius and a constructor to initialize the radius.
  • The calculateArea method computes the area of the circle using the formula π * radius * radius.
  • In the main method, an object myCircle of the class Circle is created with a radius of 5.0.
  • The calculateArea method is then called on myCircle to compute the area of the circle, which is then printed to the console.