Reputation: 39
I am taking coordinates as input like below :
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);
And constructing a triangle using :
Shape triangle = new Polygon(x[], y[], 3);
I want to check if user is entering valid coordinates. ---- Need help on this.
Upvotes: 1
Views: 1665
Reputation: 5568
The coordinates form a valid triangle if the three points are not in a line (the sum of the length of any two sides must exceed the length of the remaining side).
Therefore, using your coordinate variables, here is the triangle validation logic (using 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");
}
Upvotes: 4
Reputation: 1123
If you are using Swing, you can write code as follows
you will get value from
String cordinate_1=text_field1.getText();
And use the following method to check whether the user input is Integer or Not
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
Upvotes: 0