I am relatively new to Java, but have been reading up on how to improve the quality of my code.
I am writing a system where I take in a series of points from a file with x and y co-ordinates and by checking slopes relative to each other, am calculating and drawing a line if there is four or more co-linear points on the line. The code works and is doing what is required, but I would like to tidy up this method by reducing the if
statements, but am not sure on how to, or if it is even necessary. The parameters being passed in is an array of double
s, which are slopes relative to an origin. I am iterating this array to look for 3 or more equal slopes in a row which would give a line and adding the corresponding points and any further equal points to a set. Once a line has been found, the rest of the slopes in array are checked in similar fashion. Any advice would be appreciated.
I think it's messy, but not sure how to rectify it.
public static void checkForLines(Double[] arrayOfSlopes, Point[] tempArray)
{
int count = 0; // Keeps track of number of duplicates
int i = 1;
while (i < arrayOfSlopes.length - 1)
{
Double first = arrayOfSlopes[i];
Double next = arrayOfSlopes[i + 1];
if (first.equals(next))
// Compares two consecutive indexes in array for equality
{
count = count + 1; // If match found increase the count
if (count == 2)
// At this point a line has been found
{
SortedSet<Point> line = new TreeSet<Point>();
//Create a set to store points from this line
line.add(tempArray[0]);
line.add(tempArray[i - 1]);
line.add(tempArray[i]);
line.add(tempArray[i + 1]);
//Store four found points
int j = i + 1;
while (j + 1 < arrayOfSlopes.length - 1 && (arrayOfSlopes[j].equals(arrayOfSlopes[j + 1])))
{
line.add(tempArray[j + 1]);
//Store any other further duplicates if exist
j++;
}
if (arrayOfSlopes[j].isInfinite() && arrayOfSlopes[arrayOfSlopes.length - 1].isInfinite() ||
arrayOfSlopes[arrayOfSlopes.length - 1].equals(first))
{
line.add(tempArray[tempArray.length - 1]);
//Check the last element for equality
}
if (lines.isEmpty())
{
lines.add(line);
}
else
{
lines.add(0, line);
;
weedDuplicates(line);
}
i = j + 1; //Continue iteration from this point
}
if (count < 2)
{
i++;
}
}
else if (first.equals(next) == false)
{
count = 0;
i++;
}
}
}
count = count + 1;
with eithercount++;
or maybe++count;
. (Some people prefer the latter, and in some cases it makes for slightly more efficient code. Shouldn't make a difference here though.) Also, instances ofif(___ == false)
should be replaced withif(!___)
. – Darrel Hoffman Nov 19 '13 at 23:42