首页 > 解决方案 > 如何转换 double x1 = input.nextDouble(); 成一个数组?

问题描述

/*
(Geometry: area of a triangle) Write a program that prompts the user to enter
three points (x1, y1), (x2, y2), (x3, y3) of a triangle and displays its area.
*/
import java.util.Scanner;

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

        // Prompt the user to enter three points
        System.out.print("Enter three points for a triangle: ");
        double x1 = input.nextDouble();
        double y1 = input.nextDouble();
        double x2 = input.nextDouble();
        double y2 = input.nextDouble();
        double x3 = input.nextDouble();
        double y3 = input.nextDouble();

        // Compute the area of a triangle
        double side1 = Math.pow(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2), 0.5);
        double side2 = Math.pow(Math.pow(x3 - x2, 2) + Math.pow(y3 - y2, 2), 0.5);
        double side3 = Math.pow(Math.pow(x1 - x3, 2) + Math.pow(y1 - y3, 2), 0.5);
        double s = (side1 + side2 + side3) / 2;
        double area = Math.pow(s * (s - side1) * (s - side2) * (s - side3), 0.5);

        // Display result
        System.out.println("The area of the triangle is " + area);
    }
}

我正在使用 Java,如何转换double x1 = input.nextDouble();为 x1 到 3 和 y1 到 3 的数组?我目前正在学习如何在 java 中使用数组,但即使阅读教科书也很难理解。有人可以帮助我如何将其转换为数组吗?

标签: java

解决方案


double[] x = new double[3];
double[] y = new double[3];

现在您可以将 x1 到 x3 访问为 x[0] 到 x[2] 并且类似地访问 y。


推荐阅读