Simply reading/printing a matrix from a text file.

edited February 2017 in Questions about Code

Hi All, I'm fairly new to using arrays and I'm not sure why this code isn't working. All I'm trying to do is read a text file, convert it to a 2D array, and then be able to read that matrix given whatever "coordinates" I put inside the square brackets. In this code I'm trying to print the variable at (2,2). The file I'm reading from is just an 8x8 matrix separated by commas. My problem is everytime I try to run this, I get a NullPointerException on the println line. I apologize if i am saying matrix when i mean 2d array.

int[][] data;

void setup() {
  size(200, 200);
  int[][] data = new int[7][7];
  // Load text file as a String
  String[] stuff = loadStrings("data.csv");
  // Convert string into an array of integers using ',' as a delimiter
  for(int a=0;a<7;a++) {
    data[a] = int(split(stuff[a], ','));
  }
}

void draw() {
  println(data[2][2]);
}

Answers

  • Hi, i would rather not have to go through the use of pvectors. I mostly want to know why my code is giving me a NullPointerException.

  • I found my problem, i needed to define my array outside of the setup function so that it could be accessed in the draw function. Thanks for the input, GoToLoop.

  • edited February 2017 Answer ✓
    // forum.Processing.org/two/discussion/20598/
    // simply-reading-printing-a-matrix-from-a-text-file#Item_4
    
    // GoToLoop (2017-Feb-02)
    
    final int GRID = 8;
    final int[][] grid = new int[GRID][GRID];
    
    String[] data = loadStrings("data.csv");
    for (int r = 0; r < GRID; ++r) {
      final int[] row = int(split(data[r], ','));
      arrayCopy(row, grid[r]);
    }
    
    for (int[] row : grid)  println(str(row));
    exit();
    

    "data.csv":

    1,2,3,4,5,6,7,8
    2,3,4,5,6,7,8,1
    3,4,5,6,7,8,1,2
    4,5,6,7,8,1,2,3
    5,6,7,8,1,2,3,4
    6,7,8,1,2,3,4,5
    7,8,1,2,3,4,5,6
    8,1,2,3,4,5,6,1
    
  • Answer ✓

    @abotics:

    Your initial error was in line 5

    When you repeat the variable type it is seen as a new local variable instead of referring to line 1

    When you remove int[][] from line 5 it should work

    (Your Solution was different but also good)

  • Thanks everyone!

Sign In or Register to comment.