Java
OOP GUIDE / WORK
LINE CLASS SOLUTIONS
TASK –
PART 1 – BASIC LINE CLASS
Here is my solution:
public class
Line
{
public double x1, y1;
public double x2, y2;
public Line(double tx1, double ty1, double tx2, double ty2)
{
x1 = tx1;
y1 = ty1;
x2 = tx2;
y2 = ty2;
}
public double length()
{
double dx = x2 - x1;
double dy = y2 - y1;
return Math.sqrt(dx * dx + dy * dy);
}
public
String toString()
{
return "(" + x1 + "," + y1 + ")
to (" + x2 + "," + y2 + ")
[length="+ length() + "]";
}
}
|
TASK –
PART 2 – ARRAYLIST
Here is my
solution:
import java.util.ArrayList;
import java.util.Collections;
public class LineTester
{
public static void
main(String[] args)
{
ArrayList<Line>
al = new ArrayList<Line>();
al.add(new
Line(4,2,9,0));
al.add(new
Line(2,9,1,8));
al.add(new
Line(0,2,7,8));
al.add(new
Line(4,4,5,5));
al.add(new
Line(2,4,0,5));
for (int i=0; i<al.size(); i++)
{
System.out.println(al.get(i));
}
}
}
|
TASK –
PART 3 – IMPLEMENT COMPARABLE
Here is my
solution:
public class
Line implements Comparable
{
public double x1, y1;
public double x2, y2;
public Line(double tx1, double ty1,
double tx2, double ty2)
{
x1 = tx1;
y1 = ty1;
x2 = tx2;
y2 = ty2;
}
public double length()
{
double dx = x2 - x1;
double dy = y2 - y1;
return Math.sqrt(dx * dx + dy
* dy);
}
public String toString()
{
return "(" + x1
+ "," + y1 + ") to (" + x2 + "," + y2 + ")
[length="+ length() + "]";
}
@Override
public int compareTo(Object o)
{
Line other =
(Line)o;
if (this.length()
< other.length())
{
return -1;
}
else if (this.length()
== other.length())
{
return 0;
}
else
{
return 1;
}
}
}
|
TASK –
PART 4 – SORTING
Here is my
solution:
import java.util.ArrayList;
import java.util.Collections;
public class
LineTester
{
public static void
main(String[] args)
{
ArrayList<Line>
al = new ArrayList<Line>();
al.add(new
Line(4,2,9,0));
al.add(new
Line(2,9,1,8));
al.add(new
Line(0,2,7,8));
al.add(new
Line(4,4,5,5));
al.add(new
Line(2,4,0,5));
for (int i=0; i<al.size(); i++)
{
System.out.println(al.get(i));
}
Collections.sort(al);
System.out.println("=====");
for (int i=0; i<al.size(); i++)
{
System.out.println(al.get(i));
}
}
}
|
Here is some
sample output from the code above:
(4.0,2.0)
to (9.0,0.0) [length=5.385164807134504]
(2.0,9.0)
to (1.0,8.0) [length=1.4142135623730951]
(0.0,2.0)
to (7.0,8.0) [length=9.219544457292887]
(4.0,4.0)
to (5.0,5.0) [length=1.4142135623730951]
(2.0,4.0)
to (0.0,5.0) [length=2.23606797749979]
=====
(2.0,9.0)
to (1.0,8.0) [length=1.4142135623730951]
(4.0,4.0)
to (5.0,5.0) [length=1.4142135623730951]
(2.0,4.0)
to (0.0,5.0) [length=2.23606797749979]
(4.0,2.0)
to (9.0,0.0) [length=5.385164807134504]
(0.0,2.0) to (7.0,8.0) [length=9.219544457292887]
|
|