Java黑皮书课后题第8章:*8.15(几何:在一条直线上吗)编程练习题6.39给出了一个方法,用于测试三个点是否在一条直线上。编写下面的方法,检测points数组中所有的点是否都在同一条直线上
*8.15(几何:在一条直线上吗)编程练习题6.39给出了一个方法,用于测试三个点是否在一条直线上。编写下面的方法,检测points数组中所有的点是否都在同一条直线上
- 题目
- 题目描述与运行示例
- 破题
- 代码
题目
题目描述与运行示例
*8.15(几何:在一条直线上吗)编程练习题6.39(课本上的6.39并没有给出如果方法,实际方法在3.32给出)给出了一个方法,用于测试三个点是否在一条直线上。编写下面的方法,检测points数组中所有的点是否都在同一条直线上:
public static boolean sameLine(double[][] points)
编写一个程序,提示用户输入5个点,并且显示它们是否在同一直线上
下面是2个运行示例:
Enter five points: 3.4 2 6.5 9.5 2.3 3.5 5.5 5 -5 4
The five points are not no the same line
Enter five points: 1 1 2 2 3 3 4 4 5 5
The five points are on the same line
破题
- 主方法:声明一个二维数组points,长度为5*2(通过对象赋值)
- 主方法:提示用户输入语句
- 主方法:获取用户从控制台的输入,使用循环获取并赋值
- 主方法:调用方法sameLine,使用boolean值接收方法返回值
- 主方法:根据boolean值输出结果
- 方法sameLine:假设点为12345,只需要检测3次(123)(124)(125)即可
公式:(x1 - x0) * (y2 - y0) - (x2 - x0) * (y1 - y0)
以上结果>0则p2在线段左侧,=0则在线段上,<0则在线段右侧
以上公式只需要将x2和y2更换为对应点即可
如果结果都是=0,则返回true;反之则返回false
代码
import java.util.Scanner;public class Test8_15 {public static void main(String[] args) {//1. 主方法:声明一个二维数组points,长度为5*2(通过对象赋值)int length_row = 5, length_col = 2;double[][] points = new double[length_row][length_col];//2. 主方法:提示用户输入语句System.out.print("Enter five points: ");//3. 主方法:获取用户从控制台的输入,使用循环获取并赋值Scanner input = new Scanner(System.in);for (int i = 0 ; i < length_row ; i++){for (int j = 0 ; j <length_col ; j++){points[i][j] = input.nextDouble();}}//4. 主方法:调用方法sameLine,使用boolean值接收方法返回值boolean bool = sameLine(points);//5. 主方法:根据boolean值输出结果if (bool)System.out.println("The five points are on the same line");elseSystem.out.println("The five points are not no the same line");}public static boolean sameLine(double[][] points){//假设点为12345,只需要检测3次(123)(124)(125)即可for (int i = 2 ; i < points.length ; i++){if ((points[1][0] - points[0][0]) * (points[i][1] - points[0][1]) -(points[i][0] - points[0][0]) * (points[1][1] - points[0][1]) != 0)return false;}return true;}
}
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
