(Center of a triangle) In Java, write the following method that returns the center of a triangle:
(MAKE SURE TO USE THIS METHOD) public static Point getCenterPoint(Point p1, Point p2, Point p3);
Write a test program that prompts the user to enter three points and displays the center point.
Here is a sample run: (Hint: Use what you created for the previous problem).
Enter x1, y1, x2, y2, x3, y3: 2.5 2 5 -1.0 4.0 2.0
The center point is at (3.8333333333333335, 1.0)
Point.java
public class Point {
private double p1;
private double p2;
public double getP1() {
return p1;
}
public void setP1(double p1) {
this.p1 = p1;
}
public double getP2() {
return p2;
}
public void setP2(double p2) {
this.p2 = p2;
}
}
Driver Class
Centroid.java
import java.util.Scanner;
public class Centroid {
public static Point getCenterPoint(Point p1, Point p2, Point p3){
Point p = new Point();
double x = (p1.getP1() + p2.getP1() + p3.getP1()) / 3;
double y = (p1.getP2() + p2.getP2() + p3.getP2()) / 3;
p.setP1(x);
p.setP2(y);
return p;
}
public static void main(String[] args) {
Point p1 = new Point();
Point p2 = new Point();
Point p3 = new Point();
Point p4 = new Point();
Scanner sc = new Scanner(System.in);
System.out.println("Enter x1 and y1");
p1.setP1(sc.nextDouble());
p1.setP2(sc.nextDouble());
System.out.println("Enter x2 and y2");
p2.setP1(sc.nextDouble());
p2.setP2(sc.nextDouble());
System.out.println("Enter x3 and y3");
p3.setP1(sc.nextDouble());
p3.setP2(sc.nextDouble());
p4 = getCenterPoint(p1, p2, p3);
System.out.println("Center Point = " + p4.getP1() + ", " + p4.getP2());
}
}
Output:-
Make sure to put the two files in the same package.
Note:- Please comment if you face any problem. :)
Get Answers For Free
Most questions answered within 1 hours.