过程
public static int[] inPut(){
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
String temp[] = new String[4];
int points[] = new int[4];
Pattern pt = Pattern.compile("[0-9]+,[0-9]+,[0-9]+,[0-9]+");//判断输入格式
Matcher m = pt.matcher(s);
if(m.find()){//输入格式正确时
temp = s.split(",");//将用户的输入分解为字符串数组
points[0] = Integer.parseInt(temp[0]);//将String转换成Int
points[1] = Integer.parseInt(temp[1]);
points[2] = Integer.parseInt(temp[2]);
points[3] = Integer.parseInt(temp[3]);
return points;
}else{
System.out.println("输入有误,请重新输入。");
inPut();//重新调用自己
}
return null;
}
//得到矩形,调用Rectangle类
public static Rectangle getRectangle(int[] a){
return new Rectangle(Math.min(a[0], a[2]),Math.min(a[1], a[3]),Math.abs(a[0]-a[2]),Math.abs(a[1]-a[3]));//使用Rectangle的构造方法
}
//得到矩形的x1,y1,长度,高度
public static String getXYWidthHeight(Rectangle temp){
return temp.x+","+temp.y+","+temp.width+","+temp.height;
}
//求交集
public static String getIntersection(Rectangle aa,Rectangle bb){
Rectangle temp = aa.intersection(bb);
if(temp.isEmpty()){
return "不存在";
}else{
return getXYWidthHeight(temp);
}
}
//求并集
public static String getUnion(Rectangle aa,Rectangle bb){
Rectangle temp = aa.union(bb);
return getXYWidthHeight(temp);
}
public static void main(String[] args) {
int []a = null;//存放数字的字符串数组
int []b = null;
Rectangle aa;
Rectangle bb;
a = inPut();//调用input
b = inPut();
aa = getRectangle(a);
bb = getRectangle(b);
System.out.println(getIntersection(aa, bb));
System.out.println(getUnion(aa, bb));
}
}
10,10,20,20
30,30,40,40
不存在
10,10,30,30
| int |
height Rectangle 的高度。 |
| int |
width Rectangle 的宽度。 |
| int |
x Rectangle 左上角的 X 坐标。 |
| int |
y Rectangle 左上角的 Y 坐标。 |
| Rectangle(int x, int y, int width, int height) 构造一个新的 Rectangle,其左上角被指定为 (x,y),其宽度和高度由同名的参数指定。
|
| boolean |
isEmpty() 确定 RectangularShape 是否为空。 |
|
| Rectangle |
intersection(Rectangle r) 计算此 Rectangle 与指定 Rectangle 的交集。 |
|
| Rectangle |
union(Rectangle r) 计算此 Rectangle 与指定 Rectangle 的并集。 |
|