Java代码示例:计算用户输入的两个圆的圆心距离和面积差

本文提供了一个Java代码示例,用于计算两个圆的圆心距离和面积差,其中圆的半径和坐标由用户输入。

以下是完整的代码:javaimport java.util.Scanner;

public class Circle { private double radius; private double x; private double y;

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

public double getX() {        return this.x;    }

public double getY() {        return this.y;    }

public double getArea() {        return Math.PI * Math.pow(this.radius, 2);    }

public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);

    System.out.print('Enter the radius of the first circle: ');        double radius1 = scanner.nextDouble();        System.out.print('Enter the x-coordinate of the first circle: ');        double x1 = scanner.nextDouble();        System.out.print('Enter the y-coordinate of the first circle: ');        double y1 = scanner.nextDouble();

    Circle c1 = new Circle(radius1, x1, y1);

    System.out.print('Enter the radius of the second circle: ');        double radius2 = scanner.nextDouble();        System.out.print('Enter the x-coordinate of the second circle: ');        double x2 = scanner.nextDouble();        System.out.print('Enter the y-coordinate of the second circle: ');        double y2 = scanner.nextDouble();

    Circle c2 = new Circle(radius2, x2, y2);

    scanner.close();

    double distance = Math.sqrt(Math.pow(c1.getX() - c2.getX(), 2) + Math.pow(c1.getY() - c2.getY(), 2));        double areaDifference = Math.abs(c1.getArea() - c2.getArea());

    System.out.println('Distance between the centers: ' + distance);        System.out.println('Area difference: ' + areaDifference);    }}

代码解释:

  1. 导入Scanner类: import java.util.Scanner; 这行代码导入了Scanner类,用于从用户获取输入。

  2. 创建Circle类: 代码定义了一个名为Circle的类,该类具有以下属性和方法: - 属性: - radius: 圆的半径 - x: 圆心的x坐标 - y: 圆心的y坐标 - 方法: - Circle(double radius, double x, double y): 构造函数,用于创建Circle对象 - getX(): 返回圆心的x坐标 - getY(): 返回圆心的y坐标 - getArea(): 计算并返回圆的面积

  3. main方法: - 创建Scanner对象以获取用户输入。 - 提示用户输入两个圆的半径和坐标。 - 使用输入的值创建两个Circle对象 (c1c2)。 - 使用圆心坐标计算两个圆心之间的距离。 - 计算两个圆的面积差。 - 打印结果(距离和面积差)。 - 关闭Scanner对象。

如何运行代码:

  1. 将代码保存为名为Circle.java的文件。2. 打开命令提示符或终端,并导航到保存文件的目录。3. 使用以下命令编译代码: javac Circle.java4. 使用以下命令运行代码: java Circle

程序将提示您输入两个圆的信息,然后显示计算结果。

Java代码示例:计算用户输入的两个圆的圆心距离和面积差

原文地址: https://www.cveoy.top/t/topic/uVK 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录