A quirky problem with string arrays and Null Pointer Exception

here is a version with text() in draw, formatted as a table


/**
 * adapted from the Processing example - LoadFile 1
 * 
 * Loads a text file that contains two strings separated by a tab ('\t').
 * and then....
 */
String[] words;
String[] french;
String[] english;
int iRun, iWord;

void setup() {

  size(1200, 500);
  background(0);
  stroke(255);
  frameRate(12);

  words = loadStrings("vocab.txt");
  println("there are " + words.length + " word pairs");
  for (int i = 0; i < words.length; i++) {
    println(words[i]);
  }

  french = new String[words.length+1];
  english = new String[words.length+1]; 

  french[0]="French";
  english[0]="English";

  for (int i = 0; i < words.length; i = i+1) {
    String[] frenchEnglish = split(words[i], ' ');
    println(frenchEnglish[0]);
    int iWord=int(frenchEnglish[0]);
    println("French word ", iWord, " is ", frenchEnglish[1]);
    println("English word ", iWord, " is ", frenchEnglish[2]);
    int iPair=i+1;
    french[iPair]= frenchEnglish[1];
    english[iPair]= frenchEnglish[2];
    println("iPair = ", iPair, "    French = ", french[iPair], "    English =", english[iPair]);
  }
  for (int i=0; i < words.length+1; i++) {
    println(i, " ", french[i], " ", english[i]);
  }
  iRun=1;
  iWord=1;
  println("leaving setup ----------------------------------");
}

void draw() {

  background(0);

  // with the following line (a duplicate of the 2nd to the last line in setup) active, there is a null pointer exception
  // with the following line commented out - it runs as intended
  // for some reason the 2 strings "french[]" and "english[]" are not properly recognized in draw but they are in setup

  for (int i=0; i < words.length+1; i++) {
    //  println(i);
    //println(i, " ", french[i], " ", english[i]);
    textWithTab(i + "\t" + french[i] + "\t" + english[i], 
      110, 120+ 22*i);
  }

  for (int iSteps = 1; iSteps <= 5; iSteps++) {
    iWord = int(random(1., float(words.length)+.99));
    //   println(iWord);
    //   println(words[iWord-1]);
    // delay(200);
  }

  // exit();
}

void textWithTab(String s, float x, float y) {

  String[] sArray = s.split("\t");

  for (int i = 0; i < sArray.length; i++) {
    text(sArray[i], x, y);
    x+=211;
  }
}

/*
 the following is the "data" file vocab.txt
 
 1  oui  yes
 2  alors  so, then
 3  etre  to be
 4  faire  to do
 5  quoi  what
 
 */
2 Likes