Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save javiergamarra/c0f0427771c85e3fc15b to your computer and use it in GitHub Desktop.
Save javiergamarra/c0f0427771c85e3fc15b to your computer and use it in GitHub Desktop.
Example of reading a file of points with multiple spaces between
public static void main(final String[] args) {
final String path = args[0];
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
String line = br.readLine();
final int rows = Integer.parseInt(line);
final Point[] points = new Point[rows];
for (int i = 0; i < rows; i++) {
line = br.readLine();
final String[] values = line.trim().split(" ");
if (values.length >= 2) {
final int x = Integer.parseInt(values[0]);
final int y = Integer.parseInt(values[values.length - 1]);
points[i] = new Point(x, y);
points[i].draw();
} else {
i--;
}
}
} catch (final IOException e) {
e.printStackTrace();
}
}
@javiergamarra
Copy link
Author

Mejoras sobre el código anterior:

  • try-catch with resources
  • mejores nombres
  • menos líneas
  • evitar el splitLine.length - 2
  • ahora soporta múltiples espacios entre las dos posiciones, si hago un trim a un lado y a otro sólo me interesa la primera posición y la última
  • no se lanzan varios splits
  • quitar expresiones regulares que no hacen falta

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment