Reading a file with createReader

Hi Im trying to make a code that read data from a file. I have just copy the code from the reference page, but it doesnt work. It read an empty line after the end of the file. Don’t know why.
My file has this:
3,6
4,8
And the error is ArrayIndexOutOfBoundException.

Thenks
<void setup() {
size(100, 100);
parseFile();
}

void parseFile() {
// Open the file from the createWriter() example
BufferedReader reader = createReader(“datos.txt”);
String line = null;
int nums = new int[3];
try {
while ((line = reader.readLine()) != null) {
println(line);
nums = int(split(line, ‘,’));
printArray(nums);
int x = nums[0];
int y = nums[1];
println(x);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
} />

please format code with </> button * homework policy * asking questions

The following runs without error on my system. I changed the way that you set up the int array.

int[] nums;

void setup() {
  size(100, 100);
  parseFile();
}

void parseFile() {
  // Open the file from the createWriter() example
  BufferedReader reader = createReader("data.txt");
  String line = null;
  nums = new int[3];
  try {
    while ((line = reader.readLine()) != null) {
      println(line);
      nums = int(split(line, ','));
      printArray(nums);
      int x = nums[0];
      int y = nums[1];
      println(x);
    }
    reader.close();
  }
  catch (IOException e) {
    e.printStackTrace();
  }
}

1 Like