定义点类和矩形类,矩形类通过组合和继承的双重方法进行定义,生成矩形类的对象并对对象进行操作,比较本实验与上一实验的区别与优越性。 具体的是:通过定义点类和矩形类,矩形类通过组合和继承的双重方法进行定义(也就是说矩形类有个点对象的域,同时又继承自点类),然后生成矩形类的对象并对对象进行操作。具体的是点类有X、Y坐标两个私有域。另外有构造函数和赋值函数,以及平移方法、X轴对称方法、Y轴对称方法、原点对称方法等公有方法。矩形类有从点类继承的起始顶点X、Y坐标和对角顶点私有域。另外有构造函数和赋值函数,以及平移方法、X轴对称方法、Y轴对称方法、原点对称方法、求矩形面积方法等公有方法。 然后实现针对给定的一系列变换,经过程序处理后,输出经过变换后的矩形的起始顶点和对角顶点的坐标和矩形的面积。参见样例: 输入: 1 2 4 6 T 2 3 S 1 S 2 S 0 T 4 5 输出: (7,10)(10,14) 12
import java.util.Scanner; public class Main { public static void main(String[] args) { // TODO Auto-generated method stub Scanner in = new Scanner(System.in); float x1, x2, y1, y2; x1 = in.nextFloat(); y1 = in.nextFloat(); x2 = in.nextFloat(); y2 = in.nextFloat(); char m; Rectangle A = new Rectangle(x1,y1, y2, y2); Rectangle B=new Rectangle(x2,y2, y2, y2); Point p1 = new Point(x1, y1); Point p2 = new Point(x2, y2); while (in.hasNext()) { m = in.next().charAt(0); if (m == 'T') { float a, b; a = in.nextFloat(); b = in.nextFloat(); p1.move(a, b); p2.move(a, b); } if (m == 'S') { int c; c = in.nextInt(); if (c == 0) { A.change0(x1, y1, x2, y2); } if (c == 1) { A.change1(y1, y2); } if (c == 2) { A.change2(x2, x1); } } } p1.shuchu(); p2.shuchu(); System.out.println(" "+(int)A.length()*(int)B.length()); } } class Point { private float x, y; public Point(float x, float y) { this.x = x; this.y = y; } public Point(Point p) { x = p.x; y = p.y; } public float getX() { return x; } public float getY() { return y; } public void move(float a, float b) { x += a; y += b; } public void shuchu() { System.out.printf("(%.0f,%.0f)", x, y); } } class Rectangle extends Point { private float x,y; private Point p;//被组合的对象 public Rectangle(float x1,float y1,float x2,float y2) { super(x1,y1); this.x=x2; this.y=y2; } float getStartX() { return super.getX(); } float getStartY() { return super.getY(); } float getEndX() { return this.x; } float getEndY() { return this.y; } public void move(float a,float b) { super.move(a, b); x+=a; y+=b; } public float length() { float dx=this.x-super.getX(); float dy=this.y-super.getY(); return (float) Math.sqrt(dx*dx+dy*dy); } public void change0(float x1, float y1,float x2,float y2) { x1=-x1;y1=-y1; x2=-x2;y2=-y2; } public void change1(float y1,float y2) { y1=-y1; y2=-y2; } public void change2(float x2,float x1) { x1=-x1; x2=-x2; } }