Sunday 28 August 2016

Chapter 8 Exercise 15, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*8.15 (Geometry: same line?) Programming Exercise 6.39 gives a method for testing whether three points are on the same line. Write the following method to test whether all the points in the array points are on the same line. public static boolean sameLine(double[][] points) Write a program that prompts the user to enter five points and displays whether they are on the same line. Here are sample runs:

Enter five points: 3.4 2 6.5 9.5 2.3 2.3 5.5 5 -5 4
The five points are not on the same line

Enter five points: 1 1 2 2 3 3 4 4 5 5
The five points are on the same line



import java.util.Scanner;
 
public class ProgrammingEx8_15 {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  System.out.print("Enter five points:");
   
  double[][] points = new double[5][2];
   
  for (int i = 0; i < points.length; i++) {
   points[i][0] = input.nextDouble();
   points[i][1] = input.nextDouble();
  }
   
  if(sameLine(points)) {
   System.out.println("The five points are on the same line");
  } else {
   System.out.println("The five points are not on the same line");
  }
   
 
 }
 
 public static boolean sameLine(double[][] points){
  
   
  double x0 = points[0][0];
  double y0 = points[0][1];
  double x1 = points[1][0];
  double y1 = points[1][0];
   
  for (int i = 2; i < points.length; i++) {
   double c = (x1 - x0) * (points[i][1] - y0) - (points[i][0] - x0) * (y1 - y0);
   if (c != 0) {
    return  false;
   }
  }
   
   
  return true;
 }
 
 
}

No comments :

Post a Comment