Calculate the Area of a Circle in Java – 在Java中计算圆的面积

最后修改: 2018年 11月 11日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’ll illustrate how to calculate the area of a circle in Java.

在这个快速教程中,我们将说明如何用Java计算圆的面积。

We’ll be using the well-known math formula: r^2 * PI.

我们将使用著名的数学公式。r^2 * PI

2. A Circle Area Calculation Method

2.圆面积计算方法

Let’s first create a method that will perform the calculation:

让我们首先创建一个方法来进行计算。

private void calculateArea(double radius) {
    double area = radius * radius * Math.PI;
    System.out.println("The area of the circle [radius = " + radius + "]: " + area);
}

2.1. Passing the Radius as a Command Line Argument

2.1.将半径作为一个命令行参数来传递

Now we can read the command line argument and calculate the area:

现在我们可以读取命令行参数并计算出面积。

double radius = Double.parseDouble(args[0]);
calculateArea(radius);

When we compile and run the program:

当我们编译和运行该程序时。

java CircleArea.java
javac CircleArea 7

we’ll get the following output:

我们会得到以下输出。

The area of the circle [radius = 7.0]: 153.93804002589985

2.2. Reading the Radius from a Keyboard

2.2.从键盘上读取半径

Another way to get the radius value is to use input data from the user:

另一种获得半径值的方法是使用用户的输入数据。

Scanner sc = new Scanner(System.in);
System.out.println("Please enter radius value: ");
double radius = sc.nextDouble();
calculateArea(radius);

The output is the same as in the previous example.

输出结果与前面的例子相同。

3. A Circle Class

3.一个圆圈班

Besides calling a method to calculate the area as we saw in section 2, we can also create a class representing a circle:

除了像我们在第2节中看到的那样调用一个方法来计算面积,我们还可以创建一个代表圆的类。

public class Circle {

    private double radius;

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

    // standard getter and setter

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

    public String toString() {
        return "The area of the circle [radius = " + radius + "]: " + calculateArea();
    }
}

We should note a few things. First of all, we don’t save the area as a variable, since it is directly dependent on the radius, so we can calculate it easily. Secondly, the method that calculates the area is private since we use it in the toString() method. The toString() method shouldn’t call any of the public methods in the class since those methods could be overridden and their behavior would be different than the expected.

我们应该注意几件事。首先,我们没有将面积保存为一个变量,因为它直接依赖于半径,所以我们可以很容易地计算它。其次,计算面积的方法是私有的,因为我们在toString()方法中使用它。toString()方法不应该调用类中的任何公共方法,因为这些方法可能被重写,其行为会与预期的不同。

We can now instantiate our Circle object:

我们现在可以实例化我们的Circle对象。

Circle circle = new Circle(7);

The output will be the, of course, the same as before.

当然,输出结果将与以前一样。

4. Conclusion

4.总结

In this short and to-the-point article, we showed different ways of calculating the area of a circle using Java.

在这篇短小精悍的文章中,我们展示了用Java计算圆的面积的不同方法。

As always, complete source code can be found over on GitHub.

一如既往,完整的源代码可以在GitHub上找到over