Javaで円の面積を計算する

Javaで円の面積を計算する

1. 概要

このクイックチュートリアルでは、Javaで円の面積を計算する方法を説明します。

よく知られている数式:r^2 * PIを使用します。

2. 円の面積の計算方法

まず、計算を実行するメソッドを作成しましょう。

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

2.1. 半径をコマンドライン引数として渡す

これで、コマンドライン引数を読み取り、面積を計算できます。

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

プログラムをコンパイルして実行するとき:

java CircleArea.java
javac CircleArea 7

次の出力が得られます。

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

2.2. キーボードから半径を読む

半径値を取得する別の方法は、ユーザーからの入力データを使用することです:

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

出力は、前の例と同じです。

3. サークルクラス

セクション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();
    }
}

いくつか注意する必要があります。 まず、面積は半径に直接依存するため、変数として保存しないため、簡単に計算できます。 次に、面積を計算するメソッドは、toString()メソッドで使用するため、プライベートです。 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.

Circleオブジェクトをインスタンス化できるようになりました。

Circle circle = new Circle(7);

もちろん、出力は以前と同じになります。

4. 結論

この簡潔で重要な記事では、Javaを使用して円の面積を計算するさまざまな方法を示しました。

いつものように、完全なソースコードはover on GitHubにあります。