設計程序
在編寫圖形界面軟件的時候,經常會遇到處理兩個矩形的關系。
如圖【1】所示,矩形的交集指的是:兩個矩形重疊區的矩形,當然也可能不存在(參看【2】)。兩個矩形的並集指的是:能包含這兩個矩形的最小矩形,它一定是存在的。
本題目的要求就是:由用戶輸入兩個矩形的坐標,程序輸出它們的交集和並集矩形。
矩形坐標的輸入格式是輸入兩個對角點坐標,注意,不保證是哪個對角,也不保證順序(你可以體會一下,在桌面上拖動鼠標拉矩形,4個方向都可以的)。
輸入數據格式:
x1,y1,x2,y2
x1,y1,x2,y2
數據共兩行,每行表示一個矩形。每行是兩個點的坐標。x坐標在左,y坐標在右。坐標系統是:屏幕左上角為(0,0),x坐標水平向右增大;y坐標垂直向下增大。
要求程序輸出格式:
x1,y1,長度,高度
x1,y1,長度,高度
也是兩行數據,分別表示交集和並集。如果交集不存在,則輸出“不存在”
前邊兩項是左上角的坐標。後邊是矩形的長度和高度。
例如,用戶輸入:
100,220,300,100
150,150,300,300
則程序輸出:
150,150,150,70
100,100,200,200
例如,用戶輸入:
10,10,20,20
30,30,40,40
則程序輸出:
不存在
10,10,30,30
// 通過鼠標在平面上拖動出兩個矩形
// 求它們的“交”區域,“並”區域
// 鼠標拖動信息,通過鼠標按下,與抬起兩個點的坐標給出
import java.util.*;
class MyRect
{
private int left;
private int top;
private int right;
private int bottom;
public MyRect()
{
}
public MyRect(int x1, int y1, int x2, int y2)
{
left = x1x2 ? x1 : x2;
bottom = y1>y2 ? y1 : y2;
}
public MyRect getOverlap(MyRect rect)
{
MyRect t = new MyRect();
t.left = left > rect.left ? left : rect.left;
t.top = top > rect.top ? top : rect.top;
t.right = right < rect.right ? right : rect.right;
t.bottom = bottom < rect.bottom ? bottom : rect.bottom;
return t;
}
public MyRect getUnion(MyRect rect)
{
MyRect t = new MyRect();
t.left = left < rect.left ? left : rect.left;
t.top = top < rect.top ? top : rect.top;
t.right = right > rect.right ? right : rect.right;
t.bottom = bottom > rect.bottom ? bottom : rect.bottom;
return t;
}
public String toString()
{
int width = right-left;
int height = bottom-top;
if(width <= 0 || height <= 0) return "不存在";
return left + "," + top + "," + width + "," + height;
}
}
public class MyTest
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
String[] ss1 = scan.next().split(",");
String[] ss2 = scan.next().split(",");
MyRect a = new MyRect(Integer.parseInt(ss1[0]),Integer.parseInt(ss1[1]),
Integer.parseInt(ss1[2]),Integer.parseInt(ss1[3]));
MyRect b = new MyRect(Integer.parseInt(ss2[0]),Integer.parseInt(ss2[1]),
Integer.parseInt(ss2[2]),Integer.parseInt(ss2[3]));
System.out.println(a.getOverlap(b));
System.out.println(a.getUnion(b));
}
}