How Do I Create A Large 2D Array?

Hello,

I'm trying to create a 2D array of strings and I'm a little confused. I have the following code creating a small 2D array. Each of the "codewordlists" has 4 "codewords" in it making the alllists[] [] a 2x4 array.

String [] codewordlist0 = loadStrings("C:/Steven/Twitch/Testing Arduino Communication/Codeword Lists/codewordlist0.txt");
String [] codewordlist1 = loadStrings("C:/Steven/Twitch/Testing Arduino Communication/Codeword Lists/codewordlist1.txt");

String [][] alllists = {codewordlist0, codewordlist1};

This solution works fine here but I would like to expand my "codewordlists" to have one hundred or more. What I am trying to do is create a for() loop rather than have to manually code for every "codewordlist" as I have the two examples above. I have looked over the 2D Array tutorial but am having some trouble understanding. Thank you for the help.

Tagged:

Answers

  • Answer ✓

    I found the solution to my problem. Below is the for() loop I have.

    for(n = 0; n < 2; n++){
        alllists[n] = loadStrings(codewordlistlocation + n + codewordlistfiletype);
      }
    

    When I tried to run that code I was getting a NullPointerException error. My problem was that I didn't establish the size of the 2D array first. Once I added in the below code in the void setup() just above my for() loop everything works.

    alllists = new String[a][b];
    
  • Answer ✓

    well done!

  • Answer ✓

    here is a small example:

    String[][] source = {
      {"Apple", "Strawberry", "Banana", "Peach", "Pea", "Cherry"}, 
      {"Ape", "Cat", "Dolphin", "Whale", "Dog", "Lion"}, 
      {"Table", "Chair", "Cupboard", "Wardrobe"}, 
      {"Pillow", "Painting", "Television", "Flower"}, 
    }; 
    
    
    void setup() {
      size(900, 800);
      background(0);
    }
    
    void draw() {
      background(0);
    
      for (int n = 0; n < source.length; n++) {
        for (int n2 = 0; n2 < source[n].length; n2++) {
          text (source[n][n2], n*100+33, n2*20+20);
        }
      }
    }// func
    
Sign In or Register to comment.