Description
Youare to write a program that has to decide whether a given linesegment intersects a given rectangle.
An example:
line:start point: (4,9)
end point: (11,2)
rectangle: left-top:(1,5)
right-bottom: (7,1)
Linesegment does not intersect rectangle
Theline is said to intersect the rectangle if the line and the rectanglehave at least one point in common. The rectangle consists of fourstraight lines and the area in between. Although all input values areinteger numbers, valid intersection points do not have to lay on theinteger grid.
Input
The input consists of n test cases. The first line of the input file contains the number n.
Each following line contains one test case of the format:
xstart ystart xend yend xleft ytop xright ybottom
where (xstart, ystart) is the start and (xend, yend) the end point of the line and (xleft, ytop)
the top left and (xright, ybottom) the bottom right corner of the rectangle. The eight numbers
are separated by a blank. The terms top left and bottom right do not imply any ordering of
coordinates.
Output
For each test case in the input file, the output file should contain a line consisting either of the
letter "T" if the line segment intersects the rectangle or the letter "F" if the line segment does
not intersect the rectangle.
SampleInput
1
4 9 11 2 1 5 7 1
SampleOutput
F
package OJ; import java.util.*; public class P18_temp { public static void main(String[] args) { Scanner in = new Scanner(System.in); ArrayList<Character> results = new ArrayList<Character>(); int n = in.nextInt();//数据集数 for(int i=0; i<n; i++){ float x1 = in.nextFloat(); float y1 = in.nextFloat(); float x2 = in.nextFloat(); float y2 = in.nextFloat(); float xl = in.nextFloat(); float yl = in.nextFloat(); float xr = in.nextFloat(); float yr = in.nextFloat(); float k = (y1-y2)/(x1-x2);//求线段的斜率 float b = (x1*y2-x2*y1)/(x1-x2); //求线段与y轴的交点 if(k>=0){ float b1 = yl - k*xl; float b2 = yr - k*xr; if(b>=b1 || b<=b2) results.add('F'); else results.add('T'); } else { float b1 = yl - k*xr; float b2 = yr - k*xl; if(b>=b1 || b<=b2) results.add('F'); else results.add('T'); } } for(int i=0; i<n; i++){ System.out.println(results.get(i)); } } }