The problem Geometry point position shows how to test whether a point is on an unbounded line. Revise it to test whether a point is on a line segment. Write a program that prompts the user to enter the three points for p0, p1, and p2 and displays whether p2 is on the line segment from p0 to p1.

Breaking it down public static void main ( String [] strings ) {
Scanner input = new Scanner ( System . in );
System . out . print ( "Enter three points for p0, p1, and p2: " );
double x0 = input . nextDouble ();
double y0 = input . nextDouble ();
double x1 = input . nextDouble ();
double y1 = input . nextDouble ();
double x2 = input . nextDouble ();
double y2 = input . nextDouble ();
input . close ();
double position = calculatePosition ( x0 , y0 , x1 , y1 , x2 , y2 );
boolean isLineSegment = isOnLine ( x0 , x1 , x2 , position );
if ( isLineSegment ) {
System . out . println ( "(" + x2 + ", " + y2
+ ") is on the line segment from " + " (" + x0 + ", " + y0
+ ") to " + "(" + x1 + ", " + y1 + ")" );
} else {
System . out . println ( "(" + x2 + ", " + y2
+ ") is not on the line segment from" + " (" + x0 + ", "
+ y0 + ") to " + "(" + x1 + ", " + y1 + ")" );
}
}
private static boolean isOnLine ( double x0 , double x1 , double x2 ,
double position ) {
boolean isLineSegment = ( position <= 0.0000000001 )
&& ((( x0 <= x2 ) && ( x2 <= x1 )) || (( x0 >= x2 ) && ( x2 >= x1 )));
return isLineSegment ;
}
private static double calculatePosition ( double x0 , double y0 , double x1 ,
double y1 , double x2 , double y2 ) {
double position = ( x1 - x0 ) * ( y2 - y0 ) - ( x2 - x0 ) * ( y1 - y0 );
return position ;
}

Output ```
Enter three points for p0, p1, and p2: 1 1 2.5 2.5 1.5 1.5
(1.5, 1.5) is on the line segment from (1.0, 1.0) to (2.5, 2.5)
```

Point on line segment posted by Justin Musgrove on 09 April 2016

Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch3

Share on: Facebook Google+