I have an assignment where I am working on a Spreadsheet, that I have been handed by my instructor.
I am being asked to implement a class called Range, that accepts two positions (each consisting of two ints denoting column and row, for instance new Position(1,2)), and then finds the lowest row and column and constructs a new position which these two values, this position is the upper left corner of my range, and the same with the highest value for row and column.
Then I was asked to make a class that takes the sum of a range of positions. So I decided that for my range it should be able to have a method where all the positions where put into an ArrayList, that is the getPositions() method.
Here you can see the source code of the class:
package spreadsheet;
import java.lang.Math;
import java.util.ArrayList;
public class Range {
private Position a;
private Position b;
private ArrayList<Position> positionList;
// Creates a new range, where it makes sure that the positions,
// appear in the right order, where the first position is the position
// of the upper left corner, and the second position is the lower right corner.
public Range(final Position a, final Position b) {
int minColumn = Math.min(a.getColumn(),b.getColumn());
int minRow = Math.min(a.getRow(),b.getRow());
int maxColumn = Math.max(a.getColumn(),b.getColumn());
int maxRow = Math.max(a.getRow(),b.getRow());
this.a = new Position(minColumn, minRow);
this.b = new Position(maxColumn, maxRow);
positionList = new ArrayList<>();
}
public ArrayList<Position> getPositions() {
int minColumn = this.a.getColumn();
int minRow = this.a.getRow();
int maxColumn = this.b.getColumn();
int maxRow = this.b.getRow();
for(int i = minColumn; i < maxColumn; i++) {
for(int j = minRow; j < maxRow; j++) {
positionList.add(new Position(i, j));
}
}
return positionList;
}
}
The problem is however that it does not really work, the list it returns is empty, so why is that? Can anyone spot the error?
I see no reason why that shouldn’t work.
Ok, there are a few problems here:
positionList = new ArrayList<>();will not compile. It must bepositionList = new ArrayList<Position>();i <= maxColumnandj <= maxRowin the loops).For my test I used Points instead of Position and added some casts for Points use ints as constructor argument but return double. But I didn’t change the logic itself:
The Test:
The result:
edit:
I would see every point twice too, if I would call getPoints() a second time.
You create the list once but add points every time you call getPoints().
There are several possibilities:
2. edit
option:
option:
option: