I am trying to read in x,y coordinates in from a file separated by a comma. However, the elements are not being added to the ArrayList properly. Where am I going wrong here?
ArrayList<Double> xpointArrayList = new ArrayList<Double>();
ArrayList<Double> ypointArrayList = new ArrayList<Double>();
try {
BufferedReader input = new BufferedReader(new FileReader(args[0]));
String line;
while ((line = input.readLine()) != null) {
line = input.readLine();
String[] splitLine = line.split(",");
double xValue = Double.parseDouble(splitLine[0]);
double yValue = Double.parseDouble(splitLine[1]);
xpointArrayList.add(xValue);
ypointArrayList.add(yValue);
}
input.close();
} catch (IOException e) {
} catch (NullPointerException npe) {
}
double[] xpoints = new double[xpointArrayList.size()];
for (int i = 0; i < xpoints.length; i++) {
xpoints[i] = xpointArrayList.get(i);
}
double[] ypoints = new double[ypointArrayList.size()];
for (int i = 0; i < ypoints.length; i++) {
ypoints[i] = ypointArrayList.get(i);
}
When I do the Array.toSring call on the xpoints and the ypoints array. It only has one number. For example in the file:
1,2
3,4
0,5
It only has 3.0 for the xpoints array and 4.0 for the ypoints array. Where is it going wrong?
You just read a line, discarded it, then read another line.
Rinse, repeat (since it’s a loop).
In the future, you really should think about using the debugger. You can step through your code as it executes and see exactly what is going on. Learning to use it will be invaluable.
Edit To add: As GregHaskins points out the comments below, you also obscured the problem by catching the
NullPointerExceptionand not acting on it. On the second iteration of your loop,linewould benullon the second call toreadLine()because there was nothing left in the file. The call tosplit()then throws aNullPointerExceptionwhich you catch … then silently ignore.