my question is on a java program. i have added all instructions for this homeowr
ID: 3788656 • Letter: M
Question
my question is on a java program. i have added all instructions for this homeowrk assignment. from how the input is entered and what the output should read. We can only use conditional statements and arrays since that's all we have covered in class. ALSO WE CAN NOT USE API in our code. Can someone help me out with this assignment
Build an Intersection Check program. User inputs two points as x-y coordinates in twodimension space. Two points represent two end points of a line segment. Then, user can input second two points for the second line segment. With the two line segments, the program checks whether or not the two line segments intersect. The program displays “1” if the two line segments are crossing. Otherwise, display “0”. Please implement your algorithm in Java but not use API. Hint: use slop and intercept
Input: Four x-y coordinates that represent two point for the first line segment and two points for the second line segments
Output: 0 or 1 that represents intersection or no intersection
Example
Input: 7 8 5 12 10 10 3 10
Output: 1
Do you want to test again? Y
Input: 5 10 5 2 2 1 8 7
Output: 1
Do you want to test again? Y
Input: 10 10 3 10 6 3 6 6
Output: 0
Do you want to test again? Y
Input: 5 4 8 6 10 6 5 1
Output: 0
Do you want to test again? N
Thank you!
Explanation / Answer
import java.awt.Point;
import java.util.Scanner;
public class Solution{
public static int orientation(Point p, Point q, Point r) {
double val = (q.getY() - p.getY()) * (r.getX() - q.getX())
- (q.getX() - p.getX()) * (r.getY() - q.getY());
if (val == 0.0)
return 0; // colinear
return (val > 0) ? 1 : 2; // clock or counterclock wise
}
public static int intersect(Point p1, Point q1, Point p2, Point q2) {
int o1 = orientation(p1, q1, p2);
int o2 = orientation(p1, q1, q2);
int o3 = orientation(p2, q2, p1);
int o4 = orientation(p2, q2, q1);
if (o1 != o2 && o3 != o4)
return 1;
return 0;
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
String input="Y";
int p1x=0,p1y=0,p2x=0,p2y=0,p3x = 0,p3y=0,p4x=0,p4y=0;
while(!input.equals("N")){
System.out.print("Input:");
p1x=scanner.nextInt();
p1y=scanner.nextInt();
p2x=scanner.nextInt();
p2y=scanner.nextInt();
p3x=scanner.nextInt();
p3y=scanner.nextInt();
p4x=scanner.nextInt();
p4y=scanner.nextInt();
System.out.println("Output: "+intersect(new Point(p1x,p1y),new Point(p2x,p2y),
new Point(p3x,p3y),
new Point(p4x,p4y)));
System.out.print("Do you want to test again?");
input=scanner.next();
}
if(input.equals("N"))
System.out.println("Thank you!");
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.