Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * INFO0062 - Object-oriented programming
- * Special session (16/05/2019)
- *
- * Example of solution for the 1st question of the written examination from May 2018.
- *
- * Keep in mind that it is not the only possible solution. There are ways to write some parts of
- * the code in another manner that is still as valid as what is presented here.
- *
- * @author: J.-F. Grailet
- */
- public class LineSegment implements Cloneable, Serializable
- {
- private Point3D p1, p2;
- // Remark: int[] p1, int[] p2 also accepted
- public LineSegment(int x1, int y1, int z1, int x2, int y2, int z2)
- {
- p1 = new Point3D(x1, y1, z1);
- p2 = new Point3D(x2, y2, z2);
- }
- // Remark: providing the 3 values dx, dy and dz as an array is accepted too
- public synchronized void translate(int dx, int dy, int dz)
- {
- p1.translate(dx, dy, dz);
- p2.translate(dx, dy, dz);
- }
- public synchronized LineSegment[] split() throws ZeroSegmentException
- {
- int m_x, m_y, m_z;
- m_x = (p1.getX() + p2.getX()) / 2;
- m_y = (p1.getY() + p2.getY()) / 2;
- m_z = (p1.getZ() + p2.getZ()) / 2;
- Point3D middle = new Point3D(m_x, m_y, m_z);
- if(middle.equals(p1) || middle.equals(p2))
- throw new ZeroSegmentException();
- LineSegment[] res = new LineSegment[2];
- res[0] = new LineSegment(p1.getX(), p1.getY(), p1.getZ(), m_x, m_y, m_z);
- res[1] = new LineSegment(m_x, m_y, m_z, p2.getX(), p2.getY(), p2.getZ());
- return res;
- }
- public boolean equals(Object o)
- {
- if(!(o instanceof LineSegment))
- return false;
- LineSegment l2 = (LineSegment) o;
- if((p1.equals(l2.p1) && p2.equals(l2.p2)) || (p1.equals(l2.p2) && p2.equals(l2.p1)))
- return true;
- return false;
- }
- public int hashCode()
- {
- return p1.hashCode() + p2.hashCode();
- }
- public Object clone()
- {
- LineSegment clone = null;
- try
- {
- clone = (LineSegment) super.clone();
- clone.p1 = (Point3D) p1.clone();
- clone.p2 = (Point3D) p2.clone();
- }
- catch(CloneNotSupportedException e)
- {
- throw new InternalError("Unable to clone LineSegment object.");
- }
- return clone;
- }
- // Not asked, just for display in the Main class
- public String toString()
- {
- return p1 + " -> " + p2;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement