java - 如何转换 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 中使用数组,但即使阅读教科书也很难理解。有人可以帮助我如何将其转换为数组吗?
解决方案
double[] x = new double[3];
double[] y = new double[3];
现在您可以将 x1 到 x3 访问为 x[0] 到 x[2] 并且类似地访问 y。
推荐阅读
- flutter - “Widget”类型的值不能分配给“PreferredSizeWidget”类型的变量
- php - 从不同的记录更新产品表数量
- reactjs - 如何解决 Next.js 中的“未定义窗口”错误
- python - 将嵌套字典减少为“top-key-root-element”字典
- node.js - 节点窗口不卸载节点服务
- java - readLine() 使用 Socket 阻塞
- amazon-web-services - 用于 ALB 的 EC2 nginx 配置和 SSL
- c# - 发生异常:运行简单的 PowerShell 命令时出现 CLR/System.Management.Automation.Runspaces.PSSnapInException
- azure - 自托管 IR 将 Activity Run id 共享到 Control-M(外部调度工具)的问题
- swift - 带有MatrixSDK的模拟器上的Xcode单元测试在等待时崩溃:NSDictionary键不能为nil