java - 验证以检查我的三角形的坐标是否是 java 中的有效输入,这意味着三角形已正确构造

标签 java swing validation

我将坐标作为输入,如下所示:

System.out.print("Enter the three X coordinates for Triangle (x1cord,x2cord,x3cord) :");
int x1cord = input.nextInt();
int x2cord = input.nextInt();
int x3cord = input.nextInt();
int x[] = {x1cord,x2cord,x3cord};

System.out.print("Enter the three Y coordinates for Triangle (y1cord,y2cord,y3cord) :");
int y1cord = input.nextInt();
int y2cord = input.nextInt();
int y3cord = input.nextInt();
int y[] = {y1cord,y2cord,y3cord};

shape = FillComponent.drawTriangle(x, y);

并使用以下方法构建三角形:

Shape triangle = new Polygon(x[], y[], 3);

我想检查用户输入的坐标是否有效。 ---- 需要帮助。

最佳答案

如果三个点不在一条直线上(任意两条边的长度之和必须大于剩余边的长度),则坐标构成一个有效的三角形。

因此,使用您的坐标变量,这里是三角形验证逻辑(使用 java.awt.Point):

Point vertex1 = new Point(x1cord, y1cord);
Point vertex2 = new Point(x2cord, y2cord);
Point vertex3 = new Point(x3cord, y3cord);

double side1 = Math.abs(vertex1.distance(vertex2));
double side2 = Math.abs(vertex2.distance(vertex3));
double side3 = Math.abs(vertex3.distance(vertex1));

boolean valid = side1 + side2 > side3
             && side2 + side3 > side1
             && side3 + side1 > side2;

if (!valid) {
    System.out.println("The entered coordinates do not form a triangle");
}

关于java - 验证以检查我的三角形的坐标是否是 java 中的有效输入,这意味着三角形已正确构造,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27956822/

相关文章:

java - jTextArea,文字和图片

java - BoxLayout 在底部留下像素线

java - 如何设置关键监听器以在对 JFrame 执行的 JSplitPane 中的特定 Pane 中运行?

c# - 验证货币文本框

Java猜谜游戏

java - 如何高效地查看来自url的图片

java - 如何使这段代码更简洁?

javascript - 使用 React 获取文本而不是下拉(选择)输入的值

javascript - 验证并显示表单数组 Angular 中特定表单 Controller 的错误消息

java - 如何为线程组设置UncaughtExceptionHandler